<template>
  <!-- 控制按钮组 -->
  <div class="main">

    <section class="section">
      {{this.paths}}
      <!-- 地图 -->
      <div id="map_container" style="width: 100%; height: 400px;"></div>

      <!-- 控制按钮组 -->
      <div class="ebox">
        <el-button-group>
          <el-button type="info" icon="el-icon-circle-plus-outline" @click="drawRectangle">绘制围栏</el-button>
        </el-button-group>
      </div>
    </section>

  </div>


</template>

<script>

import { geofenceList } from '@/api/manage/fenceAPI.js'
import AMapLoader from '@amap/amap-jsapi-loader'
window._AMapSecurityConfig = {
  securityJsCode: "4f3846d5cf6d8f35fbddff03827111c5",
};

export default {
  name: "SelectLocation",
  data() {
    return {
      polygonPaths: [], // 存储绘制的多边形的经纬度
      type:[],
      clazz:[],
      carFence:{
        fenceText:'',
      },
      carFences:[],
      formData: {
        testId:0,
        carId: '',
        pageNum: 1,//当前页
        pageSize: 10,//页长
        pageTotal: 0,//总数
      },

      map: null,
      centerArr: [113.760234, 23.048884],//地图中心位置，不能为空数组【为空数组会报错】
      path: [],//以前绘制的数据
      paths: [], // 当前绘制的多边形经纬度数组
      test: [], // 当前绘制的多边形经纬度数组
      polygonItem: [], // 地图上绘制的所有多边形对象
      polyEditors: [],// 新增数据=>所有编辑对象数组
      polyEditorsBefore: [],// 以前历史数据=>进入编辑对象数组
      dialogFormVisible: false,
      formLabelWidth:'120px',
    };
  },
  mounted() {
    this.initAMap();
    this.init();
  },
  created(){

    this.testId = this.$route.params.Id;
    console.log(this.testId)
  },
  methods: {
    handleLocationSelected(longitudeAndLatitude) {
      this.$store.commit('setSelectedLongitudeAndLatitude', longitudeAndLatitude);
    },
    initAMap() {
      AMapLoader.load({
        key: "d617205580ad1f43884deefb6ea53eb2",
        version: "2.0",
        plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar',
          'AMap.MapType', 'AMap.MouseTool', 'AMap.Polygon', 'AMap.PolyEditor', 'AMap.CircleEditor'],
      }).then((AMap) => {
        this.map = new AMap.Map("map_container", {
          resizeEnable: true,
          viewMode: '3D', // 注意这里的引号
          zoom: 17,
          // 移除 pitch 属性，如果不需要特殊倾斜角度
          // pitch: 55,
          showBuildingBlock: true, // 注意这个属性可能在某些版本中不起作用
        });
        // 添加工具栏
        this.map.plugin(['AMap.ToolBar', 'AMap.Scale'], () => {
          const toolbar = new AMap.ToolBar()// 工具条
          const scale = new AMap.Scale()// 比例尺
          this.map.addControl(toolbar)
          this.map.addControl(scale)
        })
      }).catch((e) => {
        console.error('地图加载失败:', e);
      });
    },
    // 绘制多边形
    drawRectangle() {
      const This = this;
      let mouseTool = new AMap.MouseTool(this.map);
      const polygon = mouseTool.polygon({
        //polygon：绘制多边形【线段：polyline;矩形：rectangle;圆：circle】
        strokeColor: 'red',
        strokeOpacity: 0.4,
        strokeWeight: 6,
        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 = [];  // 编辑的路径
        paths.forEach(v => {
          path.push([v.lng, v.lat])
        });
        This.paths = path
        // this.paths = path.toString() //将新增数据放入paths数组里
        // This.editRectangle();//绘制完成,默认进入编辑状态
        This.polygonItem.push(event.obj);
        //  console.log(9999,this.paths)
        // sessionStorage.setItem("paths","")
        // sessionStorage.setItem("paths",path.toString());

        // This.map.remove(event.obj); // 删除多边形
        // console.log(polygon, '------polygon-----');
        console.log(paths);//控制台打印坐标
      });
    },


    //获取后台数据
    init() {
      const that = this
      let param = {
        carId: this.formData.carId,//string true carID
        pageNum: this.formData.pageNum,//string false 当前页数
        pageSize: this.formData.pageSize,//string false 每页条数
      }
      geofenceList({ param }).then(res => {
        if (res.data.code == 0) {
          if (res.data.data.list.length==0) {
            this.$message.error('没有围栏数据')
            return
          }
          that.path=[]
          that.map.clearMap(); // 删除地图所有覆盖物
          res.data.data.list.forEach((item, index) => { //同时展示多个围栏
            that.path.push(item.points)//编辑时，可以一起编辑
            // this.centerArr = that.path[0]
            // this.initMap()

            that.map.add(new AMap.Polygon({
              path: item.points,
              strokeColor: "#FF33FF",
              strokeWeight: 6,
              strokeOpacity: 0.2,
              fillOpacity: 0.4,
              fillColor: "#1791fc",
              zIndex: 50,
            }));
            that.map.setFitView();
          })
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
  }
};
</script>

<style scoped>
#map_container {
  width: 100%;
  height: 100vh;
}
.ebox {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1000; /* 确保按钮在地图之上 */
}
</style>
