<template>
  <div class="edge">
    <el-radio-group v-model="radio" :disabled="!elSwitchValue">
      <el-radio
        v-for="(item, index) in arr"
        :key="index"
        :value="(index + 1) +''"
        @change="change(item)"
      >{{ item.label }}</el-radio>
    </el-radio-group>
    <el-switch
      v-model="elSwitchValue"
      class="ml-2"
      style="--el-switch-on-color: #409eff; --el-switch-off-color: #ff4949"
      @change="elSwitchChange"
    />
    <!-- <el-dialog v-if="from != null" v-model="dialogFormVisible" title="详细信息" width="500">
      <div class="info_container">
        <el-form :model="form">
          <el-form-item
            v-for="(value, key) in from"
            :key="key"
            :label="key"
            :label-width="'120px'"
          >{{ value }}</el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            @click="
              dialogFormVisible = false;
              from = null;
            "
          >关闭</el-button>
        </div>
      </template>
    </el-dialog>-->
  </div>
</template>

<script>
export default {
  data() {
    return {
      radio: "1",
      arr: [
        {
          label: "行政边界",
          url: "./static/data/bianjie/徐泾镇.geojson",
          style: {
            polygon: {
              outerColor: "#ffee00",
              outerWidth: 5,
              innerColor: "#00c4ff",
              alpha: 0.5
            }
          }
        },
        {
          label: "村居",
          url: "./static/data/bianjie/徐泾镇村居数据.geojson",
          style: {
            polygon: {
              outerColor: "#ffee00",
              outerWidth: 3,
              innerColor: "#00c4ff",
              alpha: 0.5
            }
          }
        },
        {
          label: "责任网格",
          url: "./static/data/bianjie/徐泾镇责任网格.geojson",
          style: {
            polygon: {
              outerColor: "#ffee00",
              outerWidth: 3,
              innerColor: "#00c4ff",
              alpha: 0.5
            }
          }
        },
        {
          label: "微网格",
          url: "./static/data/bianjie/徐泾镇微网格.geojson",
          style: {
            polygon: {
              outerColor: "#ffee00",
              outerWidth: 3,
              innerColor: "#00c4ff",
              alpha: 0.5
            }
          }
        }
      ],
      elSwitchValue: true

      // from: null,
      // dialogFormVisible: false
    };
  },
  mounted() {
    window.edgeQJ = {
      geojsonDataSource: null,
      edgeEntity: null
    };
  },
  methods: {
    change(item) {
      this.remove();
      this.addGeoJson(item.url, item.style);
    },

    elSwitchChange(status) {
      this.radio == "0";
      if (status) {
        this.show();
        // this.openClick();
      } else {
        this.hide();
        // this.closeClick();
      }
    },

    show() {
      if (edgeQJ.geojsonDataSource) edgeQJ.geojsonDataSource.show = true;
      if (edgeQJ.lineEntityCollection) edgeQJ.lineEntityCollection.show = true;
      if (edgeQJ.edgeEntity) edgeQJ.edgeEntity.show = true;
    },
    hide() {
      if (edgeQJ.geojsonDataSource) edgeQJ.geojsonDataSource.show = false;
      if (edgeQJ.lineEntityCollection) edgeQJ.lineEntityCollection.show = false;
      if (edgeQJ.edgeEntity) edgeQJ.edgeEntity.show = false;
    },
    remove() {
      if (edgeQJ.geojsonDataSource != null) {
        viewer.dataSources.remove(edgeQJ.geojsonDataSource);
        edgeQJ.geojsonDataSource = null;
      }
      if (edgeQJ.lineEntityCollection != null) {
        // viewer.dataSources.remove(edgeQJ.geojsonDataSource);
        edgeQJ.lineEntityCollection.values.map(function(item) {
          viewer.entities.remove(viewer.entities.getById(item._id));
        });
        edgeQJ.lineEntityCollection.removeAll();
        edgeQJ.lineEntityCollection = null;
      }
    },
    openClick() {
      let that = this;
      if (edgeQJ.handler) return;
      // 绑定点击事件
      edgeQJ.handler = new SkyScenery.ScreenSpaceEventHandler(viewer.canvas);
      edgeQJ.handler.setInputAction(function(movement) {
        var pick = viewer.scene.pick(movement.position); // 拾取鼠标所在的entity
        if (SkyScenery.defined(pick)) {
          let entity = pick.id;
          if (!entity) return;
          if (entity.type && entity.type == "edge") {
            let cartesian = viewer.camera.pickEllipsoid(
              movement.position,
              viewer.scene.globe.ellipsoid
            );
            // 空间坐标转世界坐标(弧度)
            if (!cartesian) return;
            let cartographic = SkyScenery.Cartographic.fromCartesian(cartesian);
            if (!cartographic) return;
            // 弧度转为角度（经纬度）
            let lon = SkyScenery.Math.toDegrees(cartographic.longitude); // 经度值
            let lat = SkyScenery.Math.toDegrees(cartographic.latitude); // 纬度值
            let showEntity = SkyScenery.Cartesian3.fromDegrees(lon, lat);
            showEntity.data = entity.properties.getValue();
            that.$store.state.showEntity = showEntity;
          }
        }
      }, SkyScenery.ScreenSpaceEventType.LEFT_CLICK);
    },
    closeClick() {
      if (edgeQJ.handler) {
        edgeQJ.handler.removeInputAction(
          SkyScenery.ScreenSpaceEventType.LEFT_CLICK
        );
        edgeQJ.handler = null;
      }
      this.dialogFormVisible = false;
      this.from = null;
    },

    // 加载geojson数据
    addGeoJson(url, options) {
      // options = {
      //   point: {
      //     imgUrl: ""
      //   },
      //   polyline: {
      //     color: "#ffffff",
      //     width: 3,
      //     alpha: 0.7
      //   },
      //   polygon: {
      //     outerColor: "#ffffff",
      //     outerWidth: 3,
      //     innerColor: "#ffffff",
      //     alpha: 0.7
      //   }
      // };
      SkyScenery.GeoJsonDataSource.load(url, {
        clampToGround: true
      }).then(function(dataSource) {
        var entities = dataSource.entities.values;
        viewer.dataSources.add(dataSource);
        edgeQJ.geojsonDataSource = dataSource;

        let lineEntityCollection = new SkyScenery.EntityCollection();

        for (var i = 0; i < entities.length; i++) {
          var entity = entities[i];
          //   if (entity.billboard) {
          //     entity.billboard = undefined;
          //     entity.billboard = new SkyScenery.BillboardGraphics({
          //       image: options.point.imgUrl,
          //       width: 50,
          //       height: 50,
          //       pixelOffset: new SkyScenery.Cartesian2(0, -25),
          //       heightReference: SkyScenery.HeightReference.CLAMP_TO_GROUND
          //     });
          //   }
          //   if (entity.polyline) {
          //     entity.polyline.width = options.polyline.width;
          //     entity.polyline.material = SkyScenery.Color.fromCssColorString(
          //       options.polyline.color
          //     ).withAlpha(options.polyline.alpha); // 颜色
          //   }
          if (entity.polygon) {
            // entity.polygon.height = 6;
            // entity.polygon.outline = true; // 边框是否显示
            // entity.polygon.outlineColor = SkyScenery.Color.fromCssColorString(
            //   options.polygon.outerColor
            // ); // 边框颜色
            // entity.polygon.outlineWidth = options.polygon.outerWidth; // 边框宽度
            // entity.polygon.material = SkyScenery.Color.fromCssColorString(
            //   options.polygon.innerColor
            // ).withAlpha(options.polygon.alpha); // 填充色
            // entity.polygon.zIndex = 99;

            let line = viewer.entities.add({
              polyline: {
                positions: entity.polygon.hierarchy._value.positions,
                width: 2,
                material: SkyScenery.Color.fromCssColorString("#fff200"),
                clampToGround: true, // 这个是线覆盖模型的关键
                zIndex: 1000, // 这个是层级，但是必须clampToGround: true
                show: true
              }
            });
            lineEntityCollection.add(line);

            entity.polygon.material = new SkyScenery.ImageMaterialProperty({
              image: "/static/image/b2.png", // 图片路径
              transparent: true // 是否透明
            });
          }
          entity.type = "edge";
        }
        edgeQJ.lineEntityCollection = lineEntityCollection;
      });
    },

    addWall() {
      let that = this;
      fetch("./static/data/bianjie/徐泾镇.geojson")
        .then(resp => resp.json())
        .then(data => {
          let positions = data.features[0].geometry.coordinates[0][0];
          edgeQJ.edgeEntity = that.addDynamicWall(positions, {
            maxH: 150,
            color: "#0060fc",
            duration: 3000
          });
          this.addWater();
        });
    },
    addWater() {
      let that = this;
      fetch("./static/data/xujingzhen-hhhd.geojson")
        .then(resp => resp.json())
        .then(data => {
          // 加水
          var options = {
            frequency: 60000.0, // 控制波数的数字。
            animationSpeed: 0.01, // 控制水的动画速度的数字。
            amplitude: 20.0, // 控制水波振幅的数字。
            specularIntensity: 0.8, // 控制镜面反射强度的数字。
            baseWaterColor: "#006ab4", // rgba颜色对象基础颜色的水。#00ffff,#00baff,#006ab4
            blendColor: "#006ab4", // 从水中混合到非水域时使用的rgba颜色对象。
            height: 0, // 水体下表面与地表之间的高度
            extrudedHeight: 0.3, // 水体上表面与地表之间的高度
            clampToGround: false, //是否贴地
            opacity: 0.7, //透明度
            image: "/static/image/water.png"
          };
          data.features.map(function(feature) {
            let waterData = feature.geometry.coordinates[0][0]
              .join(",")
              .split(",")
              .map(num => Number(num));
            SkyScenery.Water(
              new SkyScenery.PolygonHierarchy(
                SkyScenery.Cartesian3.fromDegreesArray(waterData)
              ),
              options
            ).then(waterobj => {
              viewer.scene.primitives.add(waterobj);
            });
          });
        });
    },

    // 加载动态围墙
    addDynamicWall(positions, options) {
      /**
       * options = {
       *    maxH: 100,
       *    color: "#00c4ff80",
       *    duration: 3000,
       * }
       */
      // return viewer.entities.add({
      //   name: "立体墙效果",
      //   wall: {
      //     positions: positions.map(function(item) {
      //       return SkyScenery.Cartesian3.fromDegrees(item[0], item[1]);
      //     }),
      //     // 设置高度
      //     maximumHeights: new Array(positions.length).fill(options.maxH || 100),
      //     minimumHeights: new Array(positions.length).fill(0),
      //     material: new SkyScenery.DynamicWallMaterialProperty({
      //       color: SkyScenery.Color.fromCssColorString(options.color), // "#"
      //       trailImage: "/static/image/color.png",
      //       duration: options.duration || 3000 // 3000
      //     })
      //   }
      // });
      // return

      viewer.entities.add({
        name: "立体墙效果",
        wall: {
          positions: positions.map(function(item) {
            return SkyScenery.Cartesian3.fromDegrees(item[0], item[1]);
          }),
          // 设置高度
          maximumHeights: new Array(positions.length).fill(options.maxH || 100),
          minimumHeights: new Array(positions.length).fill(0),
          material: this._initWallCustomMaterialProperty({
            image: "./static/image/arrow.png",
            freely: "cross",
            direction: "-",
            count: 3,
            color: SkyScenery.Color.BLUE,
            duration: 2000
          })
        }
      });

      let tp = positions
        .join(",")
        .split(",")
        .map(num => Number(num));
      let newTp = [];
      for (let i = 0; i < tp.length; i = i + 2) {
        const lon = tp[i];
        const lat = tp[i + 1];
        const height = 250;
        newTp.push(lon);
        newTp.push(lat);
        newTp.push(height);
      }
      this.craeteDynamicShadeWallGraphics({
        positions: SkyScenery.Cartesian3.fromDegreesArrayHeights(newTp),
        color: new SkyScenery.Color.fromCssColorString("#109af2"),
        image: "./static/image/wl.png"
      });
    },

    // 动态初始化材质线
    _initWallCustomMaterialProperty(options) {
      let _that = this;
      let Cesium = SkyScenery;
      var Color = Cesium.Color,
        defaultValue = Cesium.defaultValue,
        defined = Cesium.defined,
        defineProperties = Object.defineProperties,
        Event = Cesium.Event,
        createPropertyDescriptor = Cesium.createPropertyDescriptor,
        Property = Cesium.Property,
        Material = Cesium.Material,
        MaterialType =
          options.MaterialType || "wallType" + parseInt(Math.random() * 1000);

      function WallLinkCustomMaterialProperty(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);
        this._definitionChanged = new Event();
        this._color = undefined;
        this._colorSubscription = undefined;
        this.color = options.color || Color.BLUE;
        this.duration = options.duration || 3000;
        this._time = new Date().getTime();
      }

      defineProperties(WallLinkCustomMaterialProperty.prototype, {
        isvarant: {
          get: function() {
            return false;
          }
        },
        definitionChanged: {
          get: function() {
            return this._definitionChanged;
          }
        },
        color: createPropertyDescriptor("color")
      });
      WallLinkCustomMaterialProperty.prototype.getType = function(time) {
        return MaterialType;
      };
      WallLinkCustomMaterialProperty.prototype.getValue = function(
        time,
        result
      ) {
        if (!defined(result)) {
          result = {};
        }
        result.color = Property.getValueOrClonedDefault(
          this._color,
          time,
          Color.WHITE,
          result.color
        );
        result.image = options.image;
        result.time =
          ((new Date().getTime() - this._time) % this.duration) / this.duration;
        return result;
      };
      WallLinkCustomMaterialProperty.prototype.equals = function(other) {
        return (
          this === other ||
          (other instanceof WallLinkCustomMaterialProperty &&
            Property.equals(this._color, other._color))
        );
      };
      //动态墙
      Material._materialCache.addMaterial(MaterialType, {
        fabric: {
          type: MaterialType,
          uniforms: {
            color: new Color(1.0, 0.0, 0.0, 0.5),
            image: options.image,
            time: 0
          },
          source: _that._getDirectionWallShader({
            get: true,
            count: options.count,
            freely: options.freely,
            direction: options.direction
          })
        },
        translucent: function(material) {
          return true;
        }
      });

      return new WallLinkCustomMaterialProperty(options);
    },
    /**
     * 带方向的墙体
     * @param {*} options
     */
    _getDirectionWallShader: function(options) {
      if (options && options.get) {
        var materail =
          "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
    {\n\
    czm_material material = czm_getDefaultMaterial(materialInput);\n\
    vec2 st = materialInput.st;\n\
    \n ";
        if (options.freely == "vertical") {
          //（由下到上）

          materail +=
            "vec4 colorImage = texture2D(image, vec2(fract(float(" +
            options.count +
            ")*st.t " +
            options.direction +
            " time), fract(st.s)));\n ";
        } else {
          //（逆时针）

          materail +=
            "vec4 colorImage = texture2D(image, vec2(fract(float(" +
            options.count +
            ")*st.s " +
            options.direction +
            " time), fract(st.t)));\n ";
        }
        //泛光
        materail +=
          "vec4 fragColor;\n\
    fragColor.rgb = (colorImage.rgb+color.rgb) / 1.0;\n\
    fragColor = czm_gammaCorrect(fragColor);\n ";

        materail +=
          " material.diffuse = colorImage.rgb;\n\
    material.alpha = colorImage.a;\n\
    material.emission = fragColor.rgb;\n\
    \n\
    return material;\n\
    }\n\
    ";

        return materail;
      }
    },
    //动态渐变墙
    craeteDynamicShadeWallGraphics: function(options) {
      let Cesium = SkyScenery;
      if (options && options.positions) {
        var alp = options.alp || 1,
          num = options.num || 20,
          color = options.color || Cesium.Color.RED,
          speed = options.speed || 0.003;

        var wallEntity = new Cesium.Entity();
        wallEntity.wall = {
          positions: options.positions,
          material: new Cesium.ImageMaterialProperty({
            image: options.image,
            transparent: true,
            color: new Cesium.CallbackProperty(function() {
              if (num % 2 === 0) {
                alp -= speed;
              } else {
                alp += speed;
              }

              if (alp <= 0.1) {
                num++;
              } else if (alp >= 1) {
                num++;
              }
              return color.withAlpha(alp);
            }, false)
          })
        };
        return viewer.entities.add(wallEntity);
      }
    }
  },
  computed: {
    mapStatus() {
      return this.$store.state.initMap;
    }
  },
  watch: {
    mapStatus(newVal, oldVal) {
      if (newVal) {
        // 添加围墙
        this.addWall();
        // 添加
        this.change(this.arr[0]);
      }
    }
  }
};
</script>

<style lang="less" scoped>
.edge {
  width: 420px;
  background: #00000080;
  padding-left: 15px;
  padding-right: 15px;
  border-radius: 50px;

  .el-switch {
    margin-left: 20px;
    vertical-align: top;
  }

  .el-radio {
    color: #ffffff;
  }

  .info_container {
    height: 300px;
    overflow: hidden;
    overflow-y: auto;
  }
}
</style>
