<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" :autofocus="true" />
    </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 {
        keyword:'',
        value: 500,
        fenceRead: 'fence-read-style',
        fenceEdit: 'fence-edit-style',
        fenceOverlay: null,
        fenceName: '',
        originFence: '',
        showNameField: false,

        poiPicker: null,

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

    mounted(){
      let that= this;
      
      if(localStorage.getItem("clickFence")){
        this.originFence = JSON.parse(localStorage.getItem("clickFence") )
        console.log(this.originFence, 'edit')
        this.fenceName = this.originFence.name;
        this.value = parseInt(this.originFence.fenceInfo.radius);
        localStorage.setItem("clickFence", null) 
      }
      this.initMap()

    },


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

              // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
              map.addControl(new AMap.Scale({position: 'LT'}));
          
              // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
              // map.addControl(new AMap.MapType());

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


              that.geocoder = new AMap.Geocoder({})
          });
          this.poiMarker = new AMap.Marker();
          AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {

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


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

          
          this.map = map;
          let info = this.originFence.fenceInfo;
          this.fenceOverlay = new AMap.Circle({
            center: new AMap.LngLat(info.center.lng, info.center.lat), // 圆心位置
            radius: info.radius,  //半径
            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)
          this.map.setFitView(this.fenceOverlay)
          
      },
      onSearch(){

      },
      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(){
        let originFence = this.originFence;
        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,
          fenceId: originFence.id
        };

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

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

        




      }
      



    }
}
</script>

<style scoped>

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

.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>