<!-- 灌溉项目首页 -->
<template>
<div class="map">
    <div id="container">加载数据，请稍候...</div>
    <div class="leftNavBox">
        <div class="searchBox">
            <el-select size="small" @change="searchPro()" filterable v-model="form.province" placeholder="选择省">
                <el-option label="--请选择--" value=""></el-option>
                <el-option
                    v-for="item in provinceList"
                    :key="item.adcode"
                    :label="item.name"
                    :value="item.adcode">
                </el-option>
            </el-select>
            <el-select size="small" @change="searchCity()" filterable v-model="form.city" placeholder="选择市">
                <el-option label="--请选择--" value=""></el-option>
                <el-option
                    v-for="item in cityList"
                    :key="item.adcode"
                    :label="item.name"
                    :value="item.adcode">
                </el-option>
            </el-select>
            <el-select size="small" @change="searchDis()" filterable v-model="form.district" placeholder="选择区">
                <el-option label="--请选择--" value=""></el-option>
                <el-option
                    v-for="item in districtList"
                    :key="item.adcode"
                    :label="item.name"
                    :value="item.adcode">
                </el-option>
            </el-select>
        </div>
        <div class="listBox">
            <div class="projectSearch">
                <div>项目列表</div>
                <div>
                    <el-input
                        size="small"
                        placeholder="请输入项目名称"
                        v-model="device_id"
                        suffix-icon="el-icon-search"
                        @change="getEquipList()"
                        clearable>
                    </el-input>
                </div>
            </div>
            <div class="inner">
                <div class="scroll">
                    <el-scrollbar>
                    <div class="equipList">
                        <div class="item"
                        @click="equipLocate(item)"
                        v-for="item in mapData" :key="item.device_id">
                            <img src="../../../../static/images/baseIcon.png" width="25px" alt="">
                            {{item.device_name || '设备'+item.device_id}}
                        </div>
                        <div class="item noDate" v-if="!mapData.length">暂无数据</div>
                    </div>
                    </el-scrollbar>
                </div>   
            </div>
        </div>
    </div>
</div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
//import引入的组件需要注入到对象中才能使用
components: {},
data() {
//这里存放数据
return {
  map: null,
  center: [116.3683244, 39.915085],
  zoom: 4.5,
  tileLayer1: null,
  tileLayer2: null,
  dialogFull:false,
  // 搜索
  form:{
      province:'',
      city:'',
      district:'',
  },
  provinceList:[],
  cityList:[],
  districtList:[],
  mapData:[],
  polygons:[],
  device_id:'',
  markers:[]

};
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
  initMap() {
    //创建地图
    var that = this;
    this.map = new AMap.Map("container", {
      resizeEnable: true,
      center: that.center,
      zoom: that.zoom
    });
    AMap.plugin(
      [
        "AMap.ToolBar",
        "AMap.Scale",
        "AMap.MouseTool",
        "AMap.Geocoder",
        "AMap.PolyEditor"
      ],
      () => {
        //   this.map.addControl(new AMap.ToolBar());
        this.map.addControl(new AMap.Scale({ position: "RB" }));

        this.geocoder = new AMap.Geocoder({
          city: "全国",
          radius: 1000
        });
      }
    );
    this.tileLayer1 = new AMap.TileLayer({
      tileUrl:
        "http://t{0,1,2,3,4,5,6,7}.tianditu.gov.cn/DataServer?T=img_w&tk=888bc7de1a5f14aa1b335b02e558d9b3&x=[x]&y=[y]&l=[z]",
      zIndex: 10
    }); //卫星图层
    this.tileLayer2 = new AMap.TileLayer({
      // 图块取图地址
      tileUrl:
        "http://t{0,1,2,3,4,5,6,7}.tianditu.gov.cn/DataServer?T=cta_w&tk=888bc7de1a5f14aa1b335b02e558d9b3&x=[x]&y=[y]&l=[z]",
      zIndex: 101
    });
    // this.map.add(this.tileLayer1);
    // this.map.add(this.tileLayer2);
    this.getEquipList();
    this.districtFun();
  },
  districtFun(){
      //行政区划查询
      var opts = {
          subdistrict: 1,   //返回下一级行政区
          showbiz:false  //最后一级返回街道信息
      };
      this.district = new AMap.DistrictSearch(opts);//注意：需要使用插件同步下发功能才能这样直接使用
      this.district.search('中国', (status, result)=>{
          if(status=='complete'){
              this.getData(result.districtList[0],'country');
          }
      });
  },
  getData(data,level) {
      console.log(data);
      var bounds = data.boundaries;
      if (bounds) {
          for (var i = 0, l = bounds.length; i < l; i++) {
              var polygon = new AMap.Polygon({
                  map: this.map,
                  zIndex:5,
                  bubble:true,
                  strokeWeight: 2,
                  strokeColor: 'red',
                  fillOpacity: 0.2,
                  path: bounds[i]
              });
              this.polygons.push(polygon);
          }
          this.map.setFitView();//地图自适应
      }

      var subList = data.districtList;
      //清空下一级别的下拉列表
      if (level === 'country') {
          console.log('country');
          
          this.provinceList = subList;
          this.cityList = []
          this.districtList = [];
          this.form.province=''
          this.form.city=''
          this.form.district=''
      } else if (level === 'province') {
          console.log('province');
          this.cityList = subList;
          this.districtList = [];
          this.form.city=''
          this.form.district=''
      } else if (level === 'city') {
          console.log('city');
          this.districtList = subList;
          this.form.district=''
      }  
  },
  searchPro(){
    var keyword = this.form.province; //关键字 
    console.log(this.form.province);
    console.log(this.form.city);
    console.log(this.form.district);
    if(!keyword){
        this.cityList = []
        this.districtList = [];
        this.form.city=''
        this.form.district='';
    }else{

    }

    this.search('province',keyword)
        
  },
  searchCity(){
      var keyword = this.form.city; //关键字 
      if(!keyword){
          this.districtList = [];
          this.form.district=''
          return
      }else{
      }
      this.search('city',keyword)
  },
  searchDis(){
      var keyword = this.form.district; //关键字 
      if(!keyword){
          return
      }else{

      }
      this.search('district',keyword)
  },
  search(levelSub,keyword) {
      //清除地图上所有覆盖物
      for (var i = 0, l = this.polygons.length; i < l; i++) {
          this.polygons[i].setMap(null);
      }
      console.log('keyword');
      console.log(keyword);
      console.log(this.distCluster);
      console.log(this.polygons);
      // this.distCluster.setData([
          // "113.665412,34.757975",
          // "113.671767,34.815528",
          // "113.671867,34.825528",
          // "113.735978,34.728131",
          // "120.412618,36.382612",
          // "112.985037,23.15046",
          // "126.687123,45.787618"
      // ])

      
      if(keyword){
        this.district.setLevel(levelSub); //行政区级别
        this.district.setExtensions('all');
        //行政区查询
        //按照adcode进行查询可以保证数据返回的唯一性
        this.district.search(keyword,(status, result)=>{
            if(status === 'complete'){
                this.getData(result.districtList[0],levelSub);
            }
        });
      }
  },
  getEquipList() {
    this.$axios({
      method: "POST",
      url: "/api/api_gateway?method=weather.weather.sf_page",
      data: this.qs.stringify({
        device_id:this.device_id,
        // device_name:this.device_name
      })
    }).then(res => {
      if (res.data.message == ""){
          this.mapData = res.data.data.ids
          this.renserMarkers();
      } else {
        this.$message.error(res.data.message);
      }
    });
  },
  renserMarkers(){
    // 普通标注
    this.markers=[];
    for (var i = 0; i < this.mapData.length; i += 1) {
      var title = this.mapData[i].device_name || '设备'+this.mapData[i].device_id
      var marker = new AMap.Marker({
        icon: new AMap.Icon({
          image: require("../../../../static/images/icon5.svg"), // 设别类型0
          size: new AMap.Size(40, 40), // 图标大小
          imageSize: new AMap.Size(40, 40),
          imageOffset: new AMap.Pixel(0,0) // 图标显示位置偏移量，基准点为图标左上角
        }),
        position: [this.mapData[i].lng,this.mapData[i].lat],
        zIndex: 101,
        map:this.map,
        title: title,
      });
      marker.setExtData(this.mapData[i])//添加marker 的自定义属性
      this.markers.push(marker);
      //给所有的点标注添加点击事件
      AMap.event.addListener(marker, 'click', (e) => {
        console.log(e.target.getExtData());
        var item = e.target.getExtData()
        this.$store.commit('setData',{
            name:'irrigate_id',
            val:item.device_id,
        })
        this.$router.push('irrigate');
        // this.equipMarkerClick(item);
      });
    }
    //在视野中显示所有的点
    this.map.setFitView();
  },
  equipLocate(item){
      this.map.setCenter([item.lng,item.lat]);
      this.map.setZoom(10)
  }
},
//生命周期 - 创建完成（可以访问当前this实例）
created() {

},
//生命周期 - 挂载完成（可以访问DOM元素）
mounted() {
  this.initMap()
},
beforeCreate() {}, //生命周期 - 创建之前
beforeMount() {}, //生命周期 - 挂载之前
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped lang='less'>
.map,#container {
  width: 100%;
  height: 100%;
}
.leftNavBox{
    position: absolute;
    left: 100px;
    top: 160px;
    bottom:0;
    /deep/.el-select{
        width: 1.4rem;
    }
    .listBox{
        position: relative;
        overflow: hidden;
        width: 4.25rem;
        height: 90%;
        margin-top: 16px;
        border-radius: 6px;
        background: rgba(255,255,255,.58);
        box-shadow: 0px 3px 9px 0px #a7a7a7;
        .projectSearch{
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: .15rem;
            background: #182037;
            color: #fff;
            font-size: .175rem;
            border-radius: 6px 6px 0 0;
            /deep/.el-input{
                width: 2.5rem;
            }
        }
        .inner{
            position: absolute;
            top: 57px;
            bottom: -18px;
            left: 0;
            right: 0;
            .scroll{
                height: 100%;
                overflow: auto;
                .equipList{
                    .item{
                        padding: .175rem;
                        color: #454545;
                        font-size: .175rem;
                        // background: red;
                        cursor: pointer;
                        img{
                            vertical-align: middle;
                            margin-right: 2px;
                        }
                        &:hover{
                            background: #182037;
                            color: #fff;
                        }
                    }
                    .noDate{
                        text-align: center;
                    }
                    .item.active{
                        background: darkblue;
                    }
                }
            }
            .scroll {
                height: 100%;
                overflow-y: hidden;
                }
                .el-scrollbar{
                height: 100%;
                }
                .el-scrollbar__bar{
                &.is-vertical{
                    width:100px;//滚动条宽度
                }
                }
                .el-scrollbar__wrap{
                overflow-y: auto;
                overflow-x:hidden;
                }
                .el-scrollbar__thumb {
                // 可设置滚动条颜色
                background: red;
            }
        }
    }
}
 .amap-layers .amap-markers{
    z-index: 320 !important;
}
</style>