<template>
  <div :style="{height:height+'px'}" class="statistics-map-gd">
    <el-form :inline="true" :model="searchParam" class="demo-form-inline">
      <el-form-item label="区域" prop="region">
        <el-select @change="regionChange" clearable style="width: 150px" v-model="searchParam.region"
                   size="small"
                   placeholder="请选择区域">
          <el-option v-for="(item,index) in regionList" :key="index" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="河道" prop="covalency">
        <el-select @change="covalencyChange" clearable style="width: 150px" v-model="searchParam.covalency" size="small"
                   placeholder="请选择河道">
          <el-option v-for="(item,index) in covalencyList" :key="index" :label="item.name" :value="item.code"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="clearMap" icon="el-icon-refresh-right"
                   type="primary" size="small"
                   style="background-color: #fff; border: 1px solid #ccc ; color: #666">清空
        </el-button>
      </el-form-item>
    </el-form>
    <div v-loading="loading" :style="{height:(height-40)+'px'}" id="gdMap"></div>
<!--    <el-dialog top="5vh" class="dialog" :close-on-press-escape="false" :close-on-click-modal="false" center-->
<!--               :visible.sync="visible" title="查看图片">-->
    <viewer v-show="false" v-if="image&&image.length>0" @inited="inited">
      <img :key="index" style="width: 0px" :title="item.name" :data-source="item.imageUrl" v-for="(item,index) in image">
    </viewer>
<!--      <div style="margin-top: 15px;text-align: center" v-if="visible">{{image.name}}</div>-->
<!--      <span slot="footer" class="dialog-footer">-->
<!--                  <el-button size="medium" icon="el-icon-back"-->
<!--                             @click="visible = false">返回-->
<!--                  </el-button>-->
<!--              </span>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
  import AMap from 'AMap'
  import statisticsApi from '@/api/statistics/index'

  export default {
    name: "statisticsMapGd",
    data: function () {
      return {
        loading: false,
        height: '',
        image: [],
        imgHeight: 0,
        map: {},
        regionList: [],
        covalencyList: [],
        fileList: [],
        polygons:[],
        visible: false,
        searchParam: {
          region: '',
          covalency: ''
        }
      }
    },
    components: {},
    created() {
      this.height = document.body.clientHeight - 150
      this.imgHeight = document.body.clientHeight - 270
    },
    mounted() {
      let me=this
      this.map = new AMap.Map('gdMap', {
        zooms:[10,18]
      })
      this.map.setCity('南京市',function () {
        me.map.setZoomAndCenter(12)
      })
      this.map.on("complete", function() {
        var opts = {
          subdistrict: 0,   //获取边界不需要返回下级行政区
          extensions: 'all',  //返回行政区边界坐标组等具体信息
          level: 'district'  //查询行政级别为 市
        };
        let district = new AMap.DistrictSearch(opts);
        district.search('南京', function(status, result) {
          let polygons = [];
          var bounds = result.districtList[0].boundaries;
          if (bounds) {
            for (var i = 0, l = bounds.length; i < l; i++) {
              let polygon = new AMap.Polygon({
                strokeWeight: 2,
                path: bounds[i],
                fillOpacity: 0,
                fillColor: '#fff',
                strokeColor: '#ff0000'
              });
              polygons.push(polygon);
            }
          }
          me.polygons = polygons
          me.map.add(me.polygons)
        });
        me.getMapIndex()
      })
    },
    methods: {
      inited(viewer) {
        this.$viewer = viewer
      },
      clearMap() {
        this.searchParam = {
          region: '',
          covalency: ''
        }
        this.covalencyList = []
        this.fileList = []
        this.image=[]
        this.map.clearMap()
        this.initRegionMarker()
      },
      regionChange(val) {
        this.searchParam.covalency = ''
        this.covalencyList = []
        this.fileList = []
        this.image=[]
        this.map.clearMap()
        if (val) {
          this.driverArea(val)
        } else {
          this.initRegionMarker()
        }
      },
      covalencyChange(val) {
        this.fileList = []
        this.image=[]
        this.map.clearMap()
        if (val) {
          this.getFileList(val)
        } else {
          this.initAreaMarker()
        }
      },
      getMapIndex() {
        this.loading = true
        statisticsApi.getMapIndex({type:2}).then(res => {
          this.regionList = res.data ? res.data : []
          this.initRegionMarker()
          this.loading = false
        }).catch(e => {
          this.loading = false
          this.regionList = []
        })
      },
      getFileList(code) {
        this.loading = true
        this.searchParam.covalency = code
        statisticsApi.fileList({code: code,type:2}).then(res => {
          this.fileList = res.data ? res.data : []
          this.initFileListMarker()
          this.loading = false
        }).catch(e => {
          this.fileList = []
          this.loading = false
        })
      },
      driverArea(val) {
        this.loading = true
        this.searchParam.region = val
        statisticsApi.driverArea({driverArea: val,type:2}).then(res => {
          this.covalencyList = res.data ? res.data : []
          this.initAreaMarker()
          this.loading = false
        }).catch(e => {
          this.covalencyList = []
          this.loading = false
        })
      },
      initAreaMarker() {
        let centerPoint = null
        this.map.add(this.polygons)
        this.covalencyList.map(item => {
          if (item.longitude && item.latitude) {
            let point = new AMap.LngLat(item.longitude, item.latitude)
            if (!centerPoint) {
              centerPoint = point
              this.addRegionMarker(point,item,2,'center')
            }else{
              this.addRegionMarker(point,item,2)
            }
          }
        })
      },
      initFileListMarker() {
        let me = this
        let centerPoint = null
        this.map.add(this.polygons)
        this.fileList.map(item => {
          if (item.longitude && item.latitude) {
            let point = new AMap.LngLat(item.longitude, item.latitude)
            let filter = this.fileList.filter(child => child.longitude == item.longitude && child.latitude == item.latitude)
            if (!centerPoint) {
              centerPoint = point
              this.addFileMarker(point,item,filter.length,'center')
            }else{
              this.addFileMarker(point,item,filter.length)
            }
          }
        })
      },
      initRegionMarker() {
        let centerPoint = null
        this.map.add(this.polygons)
        this.regionList.map(item => {
          if (item.longitude && item.latitude) {
            let point = new AMap.LngLat(item.longitude, item.latitude)
            if (!centerPoint) {
              centerPoint = point
              this.addRegionMarker(point,item,1,'center')
            }else{
              this.addRegionMarker(point,item,1)
            }
          }
        })
      },
      async addRegionMarker(point,item,type,center) {
        // let gdPoint = await this.convertFrom(point)
        let remark = this.initComplexCustomOverlay(point, item.name, item.count + (type==1?'条河道':'个问题'), type==1?item.id:item.code, type)
        remark.setMap(this.map)
        if(center){
          this.map.setCenter(point)
        }
      },
      async addFileMarker(point,item,num,center) {
        let me=this
        // let gdPoint = await this.convertFrom(point)
        let icon = new AMap.Icon({
          // 图标尺寸
          size: new AMap.Size(32, 35),
          // 图标的取图地址
          image: require('../../assets/img/marker-img.png'),
          // 图标所用图片大小
          imageSize: new AMap.Size(32, 35),
        });
        let marker =new AMap.Marker({
          position: point,
          icon: icon,
          offset: new AMap.Pixel(0, -0)
        });
        marker.setDraggable(true)
        marker.setLabel({
          offset: new AMap.Pixel(0, -20),  //设置文本标注偏移量
          content: "<div class='label-info'>"+(item.location+(num>1?('('+num+'张)'):''))+"</div>", //设置文本标注内容
          direction: 'right' //设置文本标注方位
        });
        marker.dataChild = item
        marker.on( 'click',function () {
          let image = me.fileList.filter(item=>item.latitude == this.dataChild.latitude&&item.longitude == this.dataChild.longitude)
          me.image = Object.assign([],image)
          me.$nextTick(function () {
            me.$viewer.show()
          })
        })
        marker.setMap(this.map);
        this.map.add(this.polygons)
        if(center){
          this.map.setCenter(point)
        }
      },
      convertFrom(point) {
        return new Promise((resolve, reject) => {
          AMap.convertFrom(point, 'gps', function (status, res) {
            if (res.info == 'ok') {
              resolve(res.locations[0])
            } else {
              resolve(null)
            }
          })
        })
      },
      initComplexCustomOverlay(mainPoint, mainName, mainNum, mainId, mainType) {
        // 创建纯文本标记
        let me = this
        let text = new AMap.Text({
          text:mainName+'<br/>'+mainNum,
          anchor:'center', // 设置文本标记锚点
          cursor:'pointer',
          clickable:true,
          title:mainName,
          style:{
            'padding': '28px 0',
            'border-radius': '50%',
            'background-color': 'rgba(0, 139, 139, 0.9)',
            'width': '92px',
            'border-width': 0,
            'text-align': 'center',
            'font-size': '14px',
            'cursor' : 'pointer',
            'color': '#ffffff'
          },
          position: mainPoint
        });
        text.on( 'mouseover',function () {
          this.setStyle({'background-color': 'rgba(225, 165, 0, 0.9)'})
        })
        text.on( 'mouseout',function () {
          this.setStyle({'background-color': 'rgba(0, 139, 139, 0.9)'})
        })

        text.on( 'click',function () {
          me.map.clearMap( )
          if (mainType == 1) {
            me.driverArea(mainId)
          } else if (mainType == 2) {
            me.getFileList(mainId)
          }
        })

        return text
      }
    }
  }
</script>

<style lang="less">
  .statistics-map-gd {
    height: inherit;
    background-color: #fff;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .12), 0 0 6px 0 rgba(0, 0, 0, .04);
    padding: 15px;

    > div {
      width: 100%;
    }

    .amap-marker-label{
      color: #fff!important;
      font-size: 12px!important;
      border-color: #ff6600!important;
      height: 20px!important;
      line-height: 20px!important;
      padding: 0 5px!important;
      font-family: "微软雅黑";
      background-color: #ff6600!important;
    }
    .dialog {
      .el-dialog {
        width: 50% !important;
      }

      .el-dialog__body {
        text-align: center !important;
      }

      img {
        width: 100%;
      }
    }

    .amap-logo,.amap-copyright {
      display: none !important;
    }
  }
</style>
