<template>
  <div>
    <yd-navbar title="添加围栏">
        <router-link to="/fence" slot="left">
            <yd-navbar-back-icon></yd-navbar-back-icon>
        </router-link>
    </yd-navbar>

    <div style="width:100%;display: flex;justify-content: center;align-items: center;  opacity:0.95;position:absolute;top: 1.65rem; z-index:999;">
      <div class="search-area" >
        <van-icon name="search" size="14px" /><input placeholder="可在此输入关键字搜索以快速定位" type="text" id="searchbar" v-model="keyword">
      </div>
      <div class="search-button" @click="searchPlace"> <span style="margin-right:4px;color:darkgray">|</span> 搜索</div>
      
      
      
    </div>


    <div class="save-cancel-bar">
      <router-link to="/fence">
        <span style="margin-left:10px;font-size:0.3rem">取消</span>
      </router-link>
      <span>单位:/米</span>
      <span style="margin-right:10px;font-size:0.3rem" @click="showNameField = true">保存</span>
    </div>
    <div class="container">
      <div class="contrl-slider" style="margin-left: 0.6rem;width:80%;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);border-radius:3px">
        <vue-slider
        v-model="value"
        @change="setRadius"
        @drag-end="afterDragHandle"
        :max="5000"
        :min="10"
        tooltip="always"
        
        ></vue-slider>
      </div>

      <div id="fence-map" class="fence-edit-style">  </div>
  

      <div style="position:absolute;width:100%;height:1px;border-top:solid 0.7px blue;top:calc(50% + 0.8rem);"></div>
      <div style="position:absolute;width:1px;height:100%;border-left:solid 0.7px blue;top:0px;left:50%;"></div>
    </div>


    <van-dialog v-model="showNameField" @confirm="postSaveData" title="围栏命名" show-cancel-button>
      <van-field v-model="fenceName" placeholder="请给围栏取个有辨别性的名字" input-align="center" />
    </van-dialog>

  </div>



</template>

<script>
import VueSlider from 'vue-slider-component'
import 'vue-slider-component/theme/default.css'
import Vue from 'vue'; 
import 'vant/lib/index.css';
import { Notify, Dialog, Field,Icon } from 'vant';
Vue.use(Notify);
Vue.use(Dialog);
Vue.use(Field);
Vue.use(Icon);


export default {
    components: {
      VueSlider
    },
    data: function () {
      return {
        value: 500,
        keyword:'',
        fenceRead: 'fence-read-style',
        fenceEdit: 'fence-edit-style',
        fenceOverlay: null,
        fenceName: '',
        showNameField: false,
        poiPicker: null,

        poiMarker:null,
        placeMarkers: [],
        placeSearchIns: null,
      }
    },

    mounted(){
      this.initMap()
    },


    methods: {
      initMap(){
          let that = this;
          var map = new AMap.Map('fence-map', {
              zoom:15,//级别
              center: [120.62, 31.32],//中心点坐标
              // viewMode:'3D',//使用3D视图
              // mapStyle: 'amap://styles/light',
              showBuildingBlock: true
          });
          AMap.plugin([
              'AMap.ToolBar',
              'AMap.Scale',
              'AMap.HawkEye',
              'AMap.MapType',
              'AMap.Geocoder',
              'AMap.PlaceSearch',
              'AMap.Geolocation'
              
          ], function(){
              // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
              map.addControl(new AMap.ToolBar({position: 'RT', offset: new AMap.Pixel(20,20)}));

              // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
              map.addControl(new AMap.Scale({position: 'LT'}));

              let autoOptions = {
                city: '全国'
              }
              that.placeSearchIns = new AMap.PlaceSearch(autoOptions);

              var geolocation = new AMap.Geolocation({
                  enableHighAccuracy: false,//是否使用高精度定位，默认:true
                  timeout: 10000,          //超过10秒后停止定位，默认：5s
                  buttonPosition:'RB',   
                  zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点

              });
              map.addControl(geolocation);
              geolocation.getCurrentPosition(function(status,result){
                  if(status=='complete'){
                      console.log(result)
                  }else{
                    console.log(result)
                  }
              });


          
              // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
              // map.addControl(new AMap.MapType());

              that.geocoder = new AMap.Geocoder({})
          });

          this.poiMarker = new AMap.Marker();
          this.map = map;

          this.fenceOverlay = new AMap.Circle({
            center: new AMap.LngLat("116.403322", "39.920255"), // 圆心位置
            radius: 500,  //半径
            strokeColor: "#F33",  //线颜色
            strokeOpacity: 1,  //线透明度
            strokeWeight: 3,  //线粗细度
            fillColor: "#ee2200",  //填充颜色
            fillOpacity: 0.35 //填充透明度
          });

          this.map.on('mapmove', function(e){
              that.fenceOverlay.setCenter(that.map.getCenter())

            })
          this.fenceOverlay.setMap(this.map)


          AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {

              var poiPicker = new PoiPicker({
                  //city:'北京',
                  input: 'searchbar'
              });


              //初始化poiPicker
              that.poiPickerReady(poiPicker);
          });

          
      },
      setRadius(e){
        let that = this;
        that.fenceOverlay.setRadius(e)
      },
      afterDragHandle(){
        this.map.setFitView(this.fenceOverlay)
      },
      poiPickerReady(poiPicker){
        
        let that = this;
        that.poiPicker = poiPicker;
        
        try {
          that.poiPicker.on('poiPicked', function(poiResult){

            
            let poi = poiResult.item
            that.keyword = poi.name;

            that.poiMarker.setMap(that.map);

            that.poiMarker.setLabel({
              content: '<div class="label-info">'+ poi.name +'</div>',
            })


            that.map.remove(that.placeMarkers);

            that.poiMarker.setPosition(poi.location);
            that.map.setCenter(that.poiMarker.getPosition());
            that.map.setZoom(15)

            
          })
        } catch (error) {
          console.log(error)
        }
        

      },
      searchPlace(){
        let that= this;
        let keyword = that.keyword;
        if(!keyword){
          this.$dialog.toast({
              mes: '关键字为空无法搜索哦!'
          })
          return;
        }
        that.poiMarker.setMap(null);
        console.log(keyword)
        that.placeSearchIns.search(keyword, function(status, result) {
          // 搜索成功时，result即是对应的匹配数据
          if(status === 'complete'){
            console.log(result, 'success')
            let pois = result.poiList.pois;
            let markerArr = []

            if(pois.length === 0){
              that.$dialog.toast({
                  mes: '关键字较为模糊,可尝试丰富下，例如加城市!'
              })
              return;
            }


            pois.forEach(item => {
              let marker = new AMap.Marker({
                map: that.map,
                position: item.location,
                label:{
                  content:'<div class="label-info">'+ item.name +'</div>',
                }
              });

              markerArr.push(marker);
            });
            that.placeMarkers = markerArr;
            that.map.setFitView(that.placeMarkers)
          }else{
            console.log(result, 'fail')
          }
        })
      },


      postSaveData(){
        if(!this.fenceName){
          this.$dialog.toast({
              mes: '请给围栏输入一个名字'
          })
          return
        }
        let that = this;
        
        let fenceInfo = {
          radius: this.value,
          center: {lat: this.fenceOverlay.getCenter().getLat(), lng: this.fenceOverlay.getCenter().getLng()}
        }

        let data = {
          userid: localStorage.getItem("userid"),
          fenceInfo: fenceInfo,
          fenceName: this.fenceName
        };

        that.$http({
              method:'post',
              url:"/addUserFence",
              data:JSON.stringify(data)
            }).then(({ data }) => {
              if(!data.success){
                that.$dialog.toast({
                    mes: data.message
                })
                return;
              }

            Notify({ type: 'success', message: '添加用户围栏成功,返回列表' });
            this.$router.push('/fence')
              console.log(data, 'add fence res')
            });

        




      }
      



    }
}
</script>

<style scoped>
.label-info{
    padding: .75rem 1.25rem;
    margin-bottom: 1rem;
    border-radius: .25rem;
    position: fixed;
    top: 1rem;
    background-color: white;
    width: auto;
    min-width: 22rem;
    border-width: 0;
    right: 1rem;
    box-shadow: 0 2px 6px 0 rgb(114 124 245 / 50%);
}

.search-area{
display: flex;justify-content: center;align-items: center;
  background: white;
  padding: 6px;
  border-radius: 2px 0 0 2px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
}
.search-button{
  display: flex;
  justify-content: center;
  align-items: center;
  background: white;
  padding: 5px;
  font-size: 12px;
  border-radius: 0 2px 2px 0;
}
#searchbar{
  width: 60vw;
  border: 0px;
  margin-left: 5px;
}



.container{
  height:100%;
}

.save-cancel-bar{
  height: 0.6rem;
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

#fence-map{
  height:calc(100vh - 1.6rem);
  width: 100%;
}
.contrl-slider{ 
  position: absolute;
  bottom: 1rem;
  height: 40px;
  width: 100%;
  z-index: 99;
  padding: 10px 20px;
  background: white;
}


</style>