<template>
  <div class="mars3d-com">
    <div class="mars3d-com" ref="mars3dContainer" style="width: 100%; height: 100%"></div>
    <div class="mars3d-box">
      <div class="mars-3d-header">
        <el-radio v-model="marsheader" label="1">多边形面</el-radio>
        <i @click="onclonemap" class="el-icon-circle-close" style="font-size:'16px'"></i>
      </div>

      <div class="mars3d-Controls">
        <div class="mars3d-item" style="margin-top: 50px;">
          <div class="mar3d-title">数据维护：</div>
          <div class="mar3d-con">
            <el-button size="mini" type="primary" @click="startDrawGraphic">绘制</el-button>
            <el-button size="mini" type="danger" @click="deleteSelectedGraphic">删除</el-button>
            <el-button size="mini" type="success" @click="updateGraphicStyle">保存</el-button>
          </div>
        </div>

        <div class="mars3d-item">
          <div class="mar3d-title">区域名称：</div>
          <div class="mar3d-con" style="margin-left: 24px;">
            <input v-model="itemdata.texttitle" placeholder="填充文字" />
          </div>
        </div>

        <div class="mars3d-item">
          <div class="mar3d-title">边框颜色：</div>
          <div class="mar3d-con">
            <el-color-picker v-model="itemdata.fillColor" size="small"/>
            <input v-model="itemdata.fillColor" placeholder="填充色" />
          </div>
        </div>

        <div class="mars3d-item">
          <div class="mar3d-title">文字颜色：</div>
          <div class="mar3d-con">
            <el-color-picker v-model="itemdata.textColor" size="small"/>
            <input v-model="itemdata.textColor" placeholder="文字颜色" />
          </div>
        </div>

        <div class="mars3d-item">
          <el-button size="mini" type="success" @click="saveArea">保存区域</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import * as mars3d from "mars3d";
// import { Cesium } from "mars3d";
import "mars3d/dist/mars3d.css";
import "mars3d-cesium/Build/Cesium/Widgets/widgets.css";

export default {
  data() {
    return {
      mars3dContainer: null,
      map: null,
      // 图层
      graphicLayer: null,
      // 开关
      selectedGraphic: null,
      // 修改图形
      itemdata: {
        // 填充色
        fillColor: "",
        // 文字颜色
        textColor: "",
        // 填充文字
        texttitle: ""
      },
      // 唯一值
      datatitle: 1,
      // 选中自定义图形
      marsheader: "1"
    };
  },
  mounted() {
    this.mars3dContainer = this.$refs.mars3dContainer;
    // 初始化Mars3D地图
    this.map = new mars3d.Map(this.mars3dContainer, {
      scene: {
        center: { lat: 42.8, lng: 90.4, alt: 150000, heading: 0, pitch: -45 },
        showSun: true,
        showMoon: true,
        showSkyBox: true,
        showSkyAtmosphere: false, // 关闭球周边的白色轮廓 map.scene.skyAtmosphere = false
        fog: true,
        fxaa: true,
        globe: {
          showGroundAtmosphere: false, // 关闭大气（球表面白蒙蒙的效果）
          depthTestAgainstTerrain: false,
          baseColor: "#546a53"
        },
        cameraController: {
          zoomFactor: 3.0,
          minimumZoomDistance: 1,
          maximumZoomDistance: 50000000,
          enableRotate: true,
          enableZoom: true
        },
        mapProjection: mars3d.CRS.EPSG3857, // 2D下展示墨卡托投影
        mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL // 2D下左右一直可以滚动重复世界地图
      },
      control: {
        // baseLayerPicker: true, // basemaps底图切换按钮
        // homeButton: true, // 视角复位按钮
        // sceneModePicker: true, // 二三维切换按钮
        // navigationHelpButton: true, // 帮助按钮
        // fullscreenButton: true, // 全屏按钮
        contextmenu: { hasDefault: true } // 右键菜单
      },
      // terrain: {
      //   url: "//data.mars3d.cn/terrain",
      //   show: true
      // },
      basemaps: [
        {
          name: "高德地图",
          // icon: "img/basemaps/gaode.png", // 假设你有一个高德地图的图标
          type: "xyz",
          url:
            "http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
          subdomains: ["1", "2", "3", "4"],
          show: true // 设置为默认显示
        }
      ]
    });

    if (this.$parent.MarsBoxareadata) {
      console.log("this.$parent.MarsBoxareadata", this.$parent.MarsBoxareadata);
      console.log(
        "this.$parent.MarsBoxareadata",
        JSON.parse(this.$parent.MarsBoxareadata, null, 2)
      );

      this.graphicLayer = new mars3d.layer.GraphicLayer();
      this.map.addLayer(this.graphicLayer);

      let a = JSON.parse(this.$parent.MarsBoxareadata, null, 2);

      console.log("a.geojsonData.features.length > 1", a.features.length > 0);
      if (a.features.length > 0) {
        a.features.forEach(item => {
          console.log("每个item", item);
          this.addDemoGraphic14(item);
        });
      }
    } else {
      console.log("执行没有绘制==============");
      // 没有修改过
      // 创建一个图形图层
      this.graphicLayer = new mars3d.layer.GraphicLayer();
      this.map.addLayer(this.graphicLayer);
    }

    // this.bindLayerPopup();
    this.bindGraphicClick();
  },
  methods: {
    // 通知父组件关闭
    onclonemap() {
      this.$parent.onclose();
    },

    addDemoGraphic14(item) {
      console.log("item============", item);
      const graphic = new mars3d.graphic.PolylineEntity({
        positions: item.geometry.coordinates, // 假设 item.geometry.coordinates[0] 包含所有点的坐标
        style: {
          width: 2, // 设置线条宽度
          color: item.properties.fillColor, // 设置线条颜色
          materialType: mars3d.MaterialType.PolylineDash, // 设置材质类型为虚线
          dashArray: [10, 5], // 设置虚线样式，10表示实线长度，5表示空白长度
          closure: true,
          label: {
            text: item.properties.texttitle, // 设置标签文字
            font_size: 13,
            color: item.properties.textColor // 设置标签文字颜色
          }
        },
        attr: { remark: "示例14" }
      });
      this.graphicLayer.addGraphic(graphic);
    },
    // 开始绘制
    startDrawGraphic() {
      console.log("执行绘画");
      if (this.selectedGraphic) {
        this.updateGraphicStyle();
      }
      const that = this;
      if (this.graphicLayer) {
        this.graphicLayer.unbindPopup();
      }
      this.graphicLayer.startDraw({
        type: "polyline",
        // maxPointNum: 2, //可以限定最大点数，2个点绘制后自动结束
        // hasMidPoint: false,
        style: {
          color: "#3d6397",
          width: 3,
          clampToGround: false,
          materialType: mars3d.MaterialType.PolylineDash, // 设置材质类型为虚线
          dashArray: [10, 5], // 设置虚线样式，10表示实线长度，5表示空白长度
          closure: true,
          label: {
            text: "未命名",
            font_size: 18,
            color: "#3d6397",
            distanceDisplayCondition: true,
            distanceDisplayCondition_far: 500000,
            distanceDisplayCondition_near: 0
          }
        },

        success: function(graphic) {
          // 为每个图形添加唯一的属性
          graphic.attr = {
            id: that.datatitle++, // 生成一个唯一的ID
            description: "这是区域 " + graphic.id + " 的描述信息"
          };
        }
      });

      // this.updateGraphicStyle();
    },

    // 在图层绑定Popup弹窗
    bindLayerPopup() {
      this.graphicLayer.bindPopup(function(event) {
        console.log("event", event);
        const data = event.graphic.style;
        const attr = {};
        // attr["类型"] = event.graphic.type;
        // attr["来源"] = "我是layer上绑定的Popup";
        // attr["备注"] = "我支持鼠标交互";
        attr["名称"] = data.label.text;
        // attr["描述"] = attr.description || "默认描述"; // 使用图形属性中的描述信息

        return mars3d.Util.getTemplateHtml({
          title: "矢量图层",
          template: "all",
          attr
        });
      });
    },

    // 绑定图形点击事件
    bindGraphicClick() {
      const that = this;
      this.graphicLayer.on(mars3d.EventType.click, function(event) {
        that.selectedGraphic = event.graphic;
        console.log("event.graphic", event.graphic);
        console.log("this.itemdata", that.itemdata);
        console.log("this.itemdata", that.itemdata.fillColor);
        that.itemdata.fillColor = event.graphic.style.color;
        that.itemdata.textColor = event.graphic.style.label.color;
        that.itemdata.texttitle = event.graphic.style.label.text;

        // 重新绑定弹窗
        that.bindLayerPopup();
      });
    },

    // 更新图形样式
    updateGraphicStyle() {
      console.log("this.selectedGraphic", this.selectedGraphic);
      console.log("this.selectedGraphic.id", this.selectedGraphic.id);

      if (this.selectedGraphic) {
        this.selectedGraphic.style.color = this.itemdata.fillColor;
        this.selectedGraphic.style.label.color = this.itemdata.textColor;
        this.selectedGraphic.style.label.text = this.itemdata.texttitle; // 修正这里

        // // 移除之前的监听器
        // map.off(mars3d.EventType.postUpdate, updateGraphicStyle);

        // // 添加新的监听器
        // map.on(mars3d.EventType.postUpdate, function (event) {
        // 	console.log("更新了", event);
        // 	// 在这里可以进行其他操作
        // });
        const graphic = this.graphicLayer.getGraphicById(
          this.selectedGraphic.id
        );

        // console.log("graphic", graphic);
        // console.dir("111111",graphic)
        // console.log("graphic", graphic.redraw());
        graphic.redraw();

        // 重新渲染地图
        // this.map.render();
        // 关闭弹窗
        this.graphicLayer.unbindPopup();

        // 清理 selectedGraphic.value
        // this.selectedGraphic = null;
      }
    },

    // 删除
    deleteSelectedGraphic() {
      if (this.selectedGraphic) {
        this.graphicLayer.removeGraphic(this.selectedGraphic);
        this.selectedGraphic = null;
      }
    },
    // 保存区域
    saveArea() {
      this.updateGraphicStyle();

      const graphics = this.graphicLayer.getGraphics();
      const features = graphics
        .map(graphic => {
          const geometry = graphic.positions; // 获取图形的坐标点
          console.log("图形坐标点:", geometry); // 调试信息

          // 将笛卡尔坐标转换为经纬度坐标
          const positions = geometry.map(point => {
            const cartographic = Cesium.Cartographic.fromCartesian(point);
            return [
              Cesium.Math.toDegrees(cartographic.longitude),
              Cesium.Math.toDegrees(cartographic.latitude)
            ];
          });

          const properties = {
            id: graphic.attr.id,
            description: graphic.attr.description,
            fillColor: graphic.style.color,
            textColor: graphic.style.label.color,
            texttitle: graphic.style.label.text
          };

          // 根据图形的类型（如多边形、线等）创建相应的GeoJSON几何对象
          let geoJSONGeometry;
          console.log("graphic.type", graphic.type);

          if (graphic.type === "polygonP") {
            geoJSONGeometry = {
              type: "polygon",
              coordinates: [positions]
            };
          } else if (graphic.type === "polygon") {
            geoJSONGeometry = {
              type: "Polygon",
              coordinates: [positions]
            };
          } else if (graphic.type === "polyline") {
            geoJSONGeometry = {
              type: "LineString",
              coordinates: positions
            };
          } else {
            // 其他类型的图形处理
            return null;
          }

          return {
            type: "Feature",
            geometry: geoJSONGeometry,
            properties: properties
          };
        })
        .filter(feature => feature !== null); // 过滤掉无效的图形

      const geoJSON = {
        type: "FeatureCollection",
        features: features
      };

      console.log("导出的GeoJSON数据", JSON.stringify(geoJSON, null, 2));

      const a = geoJSON.features;
      const formattedCoordinates = a
        .map(feature => {
          return feature.geometry.coordinates
            .map(coord => {
              return `${coord[0]}|${coord[1]}`;
            })
            .join(", ");
        })
        .join(", ");

      console.log(formattedCoordinates);
      

      this.$parent.MarsBoxareadata = JSON.stringify(geoJSON);
      this.$parent.fenceShapedata = formattedCoordinates;
      // this.$parent.submit("form");
      this.$parent.MarsBoxSwtich = false;
    }
  },
  beforeDestroy() {
    // 组件销毁前，销毁地图
    if (this.map) {
      this.map.destroy();
    }
  }
};
</script>

<style lang="scss" scoped>
.mars3d-com {
  position: relative;

  .mars3d-box {
    position: absolute;
    right: 50px;
    top: 50px;

    width: 300px;
    height: 300px;
    background: #3c444f;
    z-index: 1000;
    padding: 0 15px 15px;
    display: flex;
    flex-direction: column;
    // position: relative;
    color: #ffffff;
    border-radius: 5px;

    .mars-3d-header {
      width: 100%;
      display: flex;
      height: 45px;
      line-height: 45px;
      padding-left: 15px !important;
      padding-right: 15px !important;
      background: #2a3653;
      border: 1px solid #344c7b;
      position: absolute;
      left: 0;
      padding: 0;
      box-sizing: border-box;
      border: 10px 10px 0 0 !important;
      display: flex;
      align-items: center;
      justify-content: space-between;

      i {
        cursor: pointer;
      }
    }

    .mars3d-Controls {
      flex: 1;
      display: flex;
      flex-wrap: wrap;

      .mars3d-item {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        .mar3d-title {
          width: 100px;
        }

        .mar3d-con {
          flex: 1;
          display: flex;
          align-items: center;
        }
      }
    }
  }
}
</style>