<template>
  <div>
    <el-button @click="initFaultDraw">初始化</el-button>
        <el-button @click="clearPolygon">重新画</el-button>
    <el-button @click="openPolyEditor">打开画笔</el-button>
<!--    <router-link :to="{path:'fences'}">ghghghgh </router-link>-->
    <el-button @click="closePolyEditor">保存围栏</el-button>
    <div id="container"></div>
  </div>
</template>


<script>
import log from '@/views/monitor/job/log.vue'
var mapGaoDe = null , polygon , polyEditor , id;
import { getFencePath, listFence, saveFencePath } from '@/api/vehicle/fence'
import fences from '@/views/fence/fences/index.vue'
export default {
  computed: {
    fences() {
      return fences
    }
  },
  props:{
    id:String
  },
  data:function() {
    return {
      map: true
    };
  },

  created:function() {
    // 加载高德地图库
    var webapi = document.createElement("script");
    webapi.src = `https://webapi.amap.com/maps?v=2.0&key=defb21facca687bad1bb8e956b7d67dd&plugin=AMap.PolygonEditor&callback=onLoad`;
    // 将api文件引入到页面中，加载完毕以后就会回调函数 onLoad
    document.head.appendChild(webapi);
    var jsapi_demos = document.createElement("script");
    jsapi_demos.src = `https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js`;
    document.head.appendChild(jsapi_demos);
  },
  mounted() {
    // 页面挂载完毕，开始异步引入高德地图
    // 创建了一个回调函数，高德地图加载完毕后会调用
    window.onLoad = function() {
      // 所有关于地图的逻辑全部都在这个回调里面，
      // 保证高德地图加载完毕
      mapGaoDe = new AMap.Map("container", {
        center: [116.400274, 39.905812],
        zoom: 14,
        viewMode: '3D',
      });
      // mapGaoDe = new AMap.Map("container", {
      //   mapStyle: "amap://styles/normal", //设置地图的显示样式
      // });
      // 缩放地图到合适的视野级别
      mapGaoDe.setFitView()
    }
    id = this.id;
  },
  methods: {
    initFaultDraw(){
      var path = [];
      // [
      //   [116.403322, 39.920255],
      //   [116.410703, 39.897555],
      //   [116.402292, 39.892353],
      //   [116.389846, 39.891365]
      // ];
      // getFencePath(this.id).then(response => {
      //   console.log("初始化："+response.data)
      //   if (response.data != undefined && response.data != null && response.data != ''){
      //     // path = JSON.parse(response.data);
      //     if (path.length > 0){
      //       mapGaoDe.setCenter([path[0][0],path[0][1]])
      //       this.initPolyGon(path);
      //     }else {
      //       log.info("请先绘制坐标点");
      //     }
      //   }
      // })
      getFencePath(this.id).then(response => {
        console.log("初始化："+response.data);
        if (response.data && response.data.length > 0) {
          mapGaoDe.setCenter([response.data[0][0], response.data[0][1]]);
          this.initPolyGon(response.data);
        } else {
          alert("请先绘制坐标点");

        }
      }).catch(error => {
        console.error("获取围栏路径失败:", error);
        alert("获取围栏路径失败");
      });
    },
    openPolyEditor: function() {
      if ( polyEditor == null){
        polyEditor = new AMap.PolygonEditor(mapGaoDe, polygon)
      }
      polyEditor.open()
      polyEditor.on('addnode', function(event) {
        console.log('触发事件：addnode')
      })

      polyEditor.on('adjust', function(event) {
        alert('触发事件：adjust')
      })

      polyEditor.on('removenode', function(event) {
        alert('触发事件：removenode')

      })

      polyEditor.on('end', this.polyEditorEnd)
    },
    closePolyEditor(){
      polyEditor.close();
    },
    initPolyGon(path){
      polygon = new AMap.Polygon({
        path: path,
        strokeColor: "#FF33FF",
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillOpacity: 0.4,
        fillColor: '#1791fc',
        zIndex: 50,
        bubble: true,
      })

      mapGaoDe.add([polygon])
    },
    clearPolygon(){
      var polyArr = mapGaoDe.getAllOverlays('polygon')
      mapGaoDe.remove(polyArr);
      var polyeditorArr = mapGaoDe.getAllOverlays('polyeditor')
      mapGaoDe.remove(polyeditorArr);

    },
    polyEditorEnd(event){
      var polyEditorPath = [];
      var path = event.target.getPath();
      for (var i in path){
        polyEditorPath.push([parseFloat(path[i]['lng']) , parseFloat(path[i]['lat'])])
      }
      console.log("坐标："+JSON.stringify(polyEditorPath))
      saveFencePath({"id":id,"fencePosition":JSON.stringify(polyEditorPath)})
      this.$modal.msgSuccess("绘制成功");
      mapGaoDe = null , polygon = null , polyEditor = null , id = null;
      this.$emit("handleClose");
      // this.$router.go(0)
      this.getList()

    }

  }
}
</script>

<style scoped lang="scss">
@import "https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css";
#container {
  width: 100%;
  height: 91vh;
}
</style>

