<template>
  <div>
    <el-button class="btn" @click="drawGraph()" style="margin-bottom: 6px">绘制多边形</el-button>
    <div id="container">


    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）,
//例如：import 《组件名称》 from '《组件路径》,

import AMapLoader from "@amap/amap-jsapi-loader";
import {fenceUpdate} from "@/api/couplet/fence";

export default {
    //import引入的组件需要注入到对象中才能使用"
    name:"map-view",
    components: {AMap},
    props: {},
    data() {
      //这里存放数据"
      return {
        map:null,
        mouseTool: null, // 添加mouseTool作为组件数据属性
        _AMap: null,
        // drawGraph:{}
        drawnPoints:{},
        points:{}
      };
    },
    //计算属性 类似于data概念",
    computed: {

    },
    //监控data中的数据变化",
    watch: {},
    //方法集合",
    methods: {
      initAMap(){
        AMapLoader.load({
          key: "b5f283177b02e0bdd7f4981f4f219432", // 申请好的Web端开发者Key，首次调用 load 时必填
          version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ["AMap.Scale","AMap.MouseTool"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
        }).then((AMap) => {
            this.map=new AMap.Map("container",{
              viewMode:"3D",
              zoom:11,
              center:[116.39, 39.9],
            })
          // 解析传入的经纬度字符串

          this.mouseTool = new AMap.MouseTool(this.map);
          setTimeout(()=>{
            if (this.drawnPoints.fenceLongitudeLatitude && typeof this.drawnPoints.fenceLongitudeLatitude === 'string') {
              this.draw1()
            }
          },100)
          this.mouseTool.on("draw", this.drawReady);

        }).catch((e)=>{
            console.log(e)
        })
      },


      draw1(){
         const pathArray = this.drawnPoints.fenceLongitudeLatitude.split(';').map(coordStr => {
            const [lng, lat] = coordStr.split(',');
            return { lng: parseFloat(lng), lat: parseFloat(lat) };
          });
          // 如果经纬度数据有效，则绘制多边形
          //pathArray.every(coord => coord.lng && coord.lat)判断经纬度数据是否都有效
          if (pathArray.length > 2 && pathArray.every(coord => coord.lng && coord.lat)) {
            const polygon = this.mouseTool.Polygon({
              path: pathArray,
              strokeColor: "#FF33FF",
              strokeOpacity: 1,
              strokeWeight: 6,
              fillColor: '#1791fc',
              fillOpacity: 0.4,
              strokeStyle: "solid",
            });
            polygon.setMap(this.map);
          }
        // } else {
        //   // 如果没有传入经纬度，则保持原逻辑，等待用户点击按钮绘制
        //   this.drawGraph()
        // }
      },
      drawGraph(){
          this.mouseTool.polygon({
            strokeColor: "#FF33FF",
            strokeOpacity: 1,
            strokeWeight: 6,
            fillColor: '#1791fc',
            fillOpacity: 0.4,
            // 线样式还支持 'dashed'
            strokeStyle: "solid",
            // strokeStyle是dashed时有效
            // strokeDasharray: [30,10],
          })
      },
      drawReady(event){
        //获取绘制的点
        let path = event.obj.getPath();
        //遍历绘制的点，将经纬度转换成字符串拼接
        const coordinatesString = path.map(point => `${point.lng},${point.lat}`).join('; ');
        this.drawnPoints.fenceLongitudeLatitude=coordinatesString
        this.$message("覆盖物对象绘制完成");
        fenceUpdate(this.drawnPoints).then(res=>{
          this.$message.success("编辑成功")
          this.$router.push({path: '/couplet/fence/fence'})
        })
      }
    },

    //生命周期 - 创建完成（可以访问当前this实例）",
    created() {
    },
    //生命周期 - 挂载完成（可以访问DOM元素）",
    mounted() {
      this.initAMap()
      this.drawnPoints=this.$route.query.drawGraph

    },
    unmounted(){
    },
    beforeCreate() {
    }, //生命周期 - 创建之前",
    beforeMount() {
    }, //生命周期 - 挂载之前",
    beforeUpdate() {
    }, //生命周期 - 更新之前",
    updated() {
    }, //生命周期 - 更新之后",
    beforeDestroy() {
    }, //生命周期 - 销毁之前",
    destroyed() {
    }, //生命周期 - 销毁完成",
    activated() {
    } //如果页面有keep-alive缓存功能，这个函数会触发",
  };
</script>
<style scoped>
    #container{
      padding:0px;
      margin: 0px;
      width: 100%;
      height: 800px;
    }

</style>
