<template>
 <div >
   <!-- <el-row>

     <Button @click="drawFence">添加区域</Button>
     <Button @click="drawFence">清除区域</Button>
     <Button @click="saveRectangle">保存区域</Button>
   </el-row> -->

   <el-row style="height: 1300px;width: 100%;">
     <el-amap class="amap-box" vid="map"
              :zoom="zoom"
              :center="center"
              :amap-manager="amapManager"
              :events="events"
     >
       <el-amap-marker v-for="(u,i) in markers" :position="u.position" :key="i" :icon="icon">
       </el-amap-marker>

     </el-amap>
   </el-row>
    <el-row type="flex" justify="end" class="m_tools">
      <el-col  style="width:auto;">
        <el-button-group size="small">
          <el-button type="default" title="绘制围栏" size="small"   v-if="tools_show.place_show" v-show="!tools_show.oc_show" icon="el-icon-edit" @click="drawFence"></el-button>
          <el-button type="default" title="保存围栏" size="small"  v-if="tools_show.place_show" v-show="!tools_show.oc_show" icon="el-icon-check" @click="saveRectangle" ></el-button>
          <el-button type="default" title="清除" size="small"v-if="tools_show.place_show" v-show="!tools_show.oc_show" icon="el-icon-delete" @click="delemap"></el-button>
          <el-button type="default" title="展开/收起" size="small" v-if="tools_show.openclose_show" :icon="tools_show.oc_show?'el-icon-d-arrow-left':'el-icon-d-arrow-right'" @click="tools_show.oc_show=!tools_show.oc_show"></el-button>
        </el-button-group>
      </el-col>

    </el-row>

  </div>


</template>

<script>
import VueAMap from 'vue-amap'

let amapManager = new VueAMap.AMapManager()
window._AMapSecurityConfig = {
  securityJsCode: 'b672db78212bb58899d609f0ce9f2d97'
}

export default {
  name: "Map",
  data() {
    return {
      // 地图对象
      amapManager,
      zoom: 12,
      center: [116.404269,39.916042],
      position: [121.5273285, 31.21515044],
      events: {
        init (o) {

        }
      },

      icon: new AMap.Icon({
        image: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png"
      }),
      searchOption: {
        city: '北京',
        citylimit: false
      },
      fenceForm:{
        coordinate:[]
      },
      rectangle:null,
      mouseTool: null,
      overlays: [],
      map: null,
      markers: [//标记点位置
        
      ],
      formData: {
        carId: '',
        pageNum: 1,//当前页
        pageSize: 10,//页长
        pageTotal: 0,//总数
      },
      map: null,
      path: [],//以前绘制的数据
      paths: [], // 当前绘制的多边形经纬度数组
      polygonItems: [], // 地图上绘制的所有多边形对象
      polyEditors: [],// 新增数据=>所有编辑对象数组
      polyEditorsBefore: [],// 以前历史数据=>进入编辑对象数组

      // 总条数
      tools_show: {
        place_show:true,
        openclose_show:true,
        oc_show:false
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fenceName: null,
        deptId: null,
      },
      // 表单参数
      form: {}
    };
  },
  watch: {

  },
  mounted() {
    //DOM初始化完成进行地图初始化
    //this.initAMap()
  },
  methods: {
    // 绘制多边形
    drawFence() {
      let _this = this
      this.map = this.amapManager.getMap()
      let map = this.amapManager.getMap()
      /* if(this.fenceForm.coordinate.length >0){
         this.$Message.warning("围栏已存在!")
         return
       }*/
      if(this.rectangle){
        map.remove(this.rectangle)
      }
      map.plugin(['AMap.MouseTool'], function () {
        let mouseTool = new AMap.MouseTool(map)
        _this.mouseTool = mouseTool
        //添加事件
        /*mouseTool.rectangle()
        AMap.event.addListener(mouseTool, 'draw', function (e) {
          _this.fenceForm.coordinate = []
          let path = e.obj.getPath()
          path.forEach(e=>{
            _this.fenceForm.coordinate.push([e.getLng(),e.getLat()])
          })
          mouseTool.close(false)
        })*/
        const polygon = mouseTool.polygon({
          //polygon：绘制多边形【线段：polyline;矩形：rectangle;圆：circle】
          strokeColor: 'red',
          strokeOpacity: 0.4,
          strokeWeight: 2,//线宽
          fillColor: '#1791fc', //填充色
          fillOpacity: 0.2,//填充透明度
          // strokeStyle还支持 solid
          strokeStyle: 'solid',
          // strokeDasharray: [30,10],
        });
        mouseTool.on('draw', function (event) {
          // event.obj 为绘制出来的覆盖物对象
          let polygonItem = event.obj;
          let paths = polygonItem.getPath();//取得绘制的多边形的每一个点坐标
          // console.log('覆盖物对象绘制完成各个点的坐标', paths, event);

          let path_in = [];  // 编辑的路径
          paths.forEach(v => {
            path_in.push([v.lng, v.lat])
            _this.fenceForm.coordinate.push([v.lng, v.lat])
          });
          _this.paths = path_in //将新增数据放入paths数组里
          _this.path = path_in //将新增数据放入paths数组里

          //this.editRectangle();//绘制完成,默认进入编辑状态
          var polygonItems=[];
           polygonItems .push(event.obj);
          //this.map.remove(event.obj); // 删除多边形
           console.log(_this.paths, '------polygon-----');
        });
      })
    },
    // 编辑围栏
    editRectangle() {
      const path = this.paths;
      //新增的进入编辑状态
      let polygon = new AMap.Polygon({
        path: path,
        strokeColor: "#FF33FF",
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillOpacity: 0.2,
        fillColor: '#1791fc',
        zIndex: 50,
      });
      this.map.add(polygon);
      this.polygonItem.push(polygon);
      // 缩放地图到合适的视野级别
      this.map.setFitView([polygon]);

      this.polyEditor = new AMap.PolyEditor(this.map, polygon);
      this.polyEditor.open();
      this.polyEditors.push(this.polyEditor);

      //历史围栏的进入编辑状态
      let polygonBefore = new AMap.Polygon({
        path: this.path,
        strokeColor: "#FF33FF",
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillOpacity: 0.2,
        fillColor: '#1791fc',
        zIndex: 50,
      });
      this.map.add(polygonBefore);
      this.polygonItem.push(polygonBefore);
      // 缩放地图到合适的视野级别
      this.map.setFitView([polygonBefore]);

      this.polyEditorBefore = new AMap.PolyEditor(this.map, polygonBefore);
      this.polyEditorBefore.open();
      this.polyEditorsBefore.push(this.polyEditorBefore);

      // this.polyEditor.on('addnode', function (event) {
      //     console.info('触发事件：addnode', event)
      //     console.info('修改后的经纬度：', polygon.getPath())
      // });

      // this.polyEditor.on('adjust', function (event) {
      //     console.info('触发事件：adjust', event)
      //     console.info('修改后的经纬度：', polygon.getPath())
      // });

      // this.polyEditor.on('removenode', function (event) {
      //     console.info('触发事件：removenode', event)
      //     console.info('修改后的经纬度：', polygon.getPath())
      // });

      // this.polyEditor.on('end', function (event) {
      //     console.info('触发事件： end', event)
      //     console.info('end修改后的经纬度：', polygon.getPath())
      //     // event.target 即为编辑后的多边形对象
      // });
    },
    // 取消编辑状态
    cancelRectangle() {
      this.polyEditors.forEach(item => { item.close(); });//新增
      this.polyEditorsBefore.forEach(item => { item.close(); });//历史
    },
    //保存围栏
    saveRectangle() {
      console.log(this.path,'---save----');
      //保存更新围栏经纬度
      let polygon="";
      var polygon_start="POLYGON((";
        this.path.forEach(v => {
          polygon=polygon+v[0]+" "+v[1]+",";
        });

      let result = polygon_start+polygon.slice(0, polygon.length - 1)+","+polygon.split(",")[0]+"))";
      let id = this.$route.params.fenceId
      let fencePolygon={fenceId:id,fencePolygon:result};
      

    },
    // 删除围栏
    deleRectangle() {
      this.map.clearMap(); // 删除地图所有覆盖物
      //删除=>成功（重新刷新页面）
    },
    delemap() {
      this.map.clearMap(); // 删除地图所有覆盖物
    },

  }
};
</script>

<style lang="scss" scoped>
  ::v-deep .amap-logo {
    display: none;
    opacity: 0 !important;
  }
  ::v-deep .amap-copyright {
    opacity: 0;
  }
</style>
<style lang="scss" scoped>
  .m_tools {
    position: absolute;
    z-index: 999;
    // left: 550px;
    // top: 120px;
    left: 85%;
    top: 1px;
    width: auto;
    color: #409eff;
    overflow: hidden;
  }
</style>
