"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _cesium = require("cesium");
var _transformRgb = _interopRequireDefault(require("../_util/transformRgb"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var glsl = "\n  czm_material czm_getMaterial(czm_materialInput materialInput) {\n    czm_material material = czm_getDefaultMaterial(materialInput);\n    vec2 st = materialInput.st;\n    // vec2 st = materialInput.st * repeat;\n    vec4 colorImage = texture2D(image, vec2(fract((st.s - speed * czm_frameNumber * 0.001)), st.t));\n    material.alpha = colorImage.a;\n    material.diffuse = colorImage.rgb;\n    return material;\n  }";

// 创建圆形
function computeCircle(radius) {
  var positions = [];
  for (var i = 0; i < 360; i++) {
    var radians = _cesium.Math.toRadians(i);
    positions.push(new _cesium.Cartesian2(radius * Math.cos(radians), radius * Math.sin(radians)));
  }
  return positions;
}

// 创建方形
function computeSquare(size) {
  return [new _cesium.Cartesian2(-size, -size),
  // 左上角
  new _cesium.Cartesian2(size, -size),
  // 右上角
  new _cesium.Cartesian2(size, size),
  // 右下角
  new _cesium.Cartesian2(-size, size) // 左下角
  ];
}
var getMultiPoints = function getMultiPoints(data) {
  var points = {};
  data.map(function (first) {
    var first_start = first.start.join(',');
    var first_end = first.end.join(',');
    data.map(function (two) {
      var two_start = two.start.join(',');
      var two_end = two.end.join(',');
      var key, value;
      if (first_start === two_start && first_end !== two_end) {
        key = first_start;
        value = [first.end, first.start, two.end];
      } else if (first_start === two_end && first_end !== two_start) {
        key = first_start;
        value = [first.end, first.start, two.start];
      } else if (first_end === two_start && first_start !== two_end) {
        key = first_end;
        value = [first.start, first.end, two.end];
      } else if (first_end === two_end && first_start !== two_start) {
        key = first_end;
        value = [first.start, first.end, two.start];
      }
      if (key && value) {
        if (points[key]) {
          points[key].push(value);
        } else {
          points[key] = [value];
        }
      }
    });
  });
  return points;
};
function createGradientImage(canvasId, startColor, endColor) {
  // 获取canvas元素
  var canvas = document.createElement('canvas');

  // 设置canvas的尺寸
  canvas.width = 512;
  canvas.height = 32;

  // 获取绘图上下文
  var ctx = canvas.getContext('2d');

  // 创建一个线性渐变
  // 假设我们想要从左到右的渐变，你也可以根据需要调整渐变的方向
  var gradient = ctx.createLinearGradient(0, 0, 512, 0);

  // 设置渐变的起始颜色和结束颜色
  // 如果startColor是'transparent'，则直接使用，否则你可能需要转换它
  // 这里我们假设startColor已经是有效的CSS颜色字符串，或者你可以添加转换逻辑
  gradient.addColorStop(0, startColor || 'transparent'); // 开始是透明的
  gradient.addColorStop(1, endColor); // 结束是传入的色值

  // 使用渐变填充整个canvas
  ctx.fillStyle = gradient;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  return canvas.toDataURL();
}
var ThreeLineLayer = /*#__PURE__*/function () {
  function ThreeLineLayer(options) {
    var _this$data;
    _classCallCheck(this, ThreeLineLayer);
    var _options$show = options.show,
      show = _options$show === void 0 ? true : _options$show;
    this.map = options.map;

    // 图层标识
    this.key = options.key;

    // 图层名称
    this.name = options.name;

    // 标签字段
    this.labelField = options.labelField;

    // 模版内容
    this.template = options.template;

    // 图例
    this.legend = options.legend;

    // 图层控制
    this.layerControl = options.layerControl;

    // 取消气泡
    this.cancelPopup = options.cancelPopup;

    // 气泡模板
    this.tipTemplate = options.tipTemplate;

    // 仅展示
    this.viewOnly = options.viewOnly;
    this.data = options.data;
    this.color = options.color;
    this.primitives = [];
    this.show = show;
    if ((_this$data = this.data) !== null && _this$data !== void 0 && _this$data.length) {
      this.loadData(this.data);
    }
  }
  return _createClass(ThreeLineLayer, [{
    key: "show",
    set: function set(value) {
      var _this$primitives;
      if ((_this$primitives = this.primitives) !== null && _this$primitives !== void 0 && _this$primitives.length) {
        this.primitives.map(function (primitive) {
          primitive.show = value;
        });
      }
    }
  }, {
    key: "loadData",
    value: function loadData(data) {
      var _this = this;
      this.data = data;
      var map = this.map;
      var show = this.show;
      this.destroy();
      this.primitives = [];
      var colors = {};

      // getMultiPoints(data);

      data.map(function (item) {
        var start = item.start,
          end = item.end,
          radius = item.radius;
        var positions = item.data ? _toConsumableArray(item.data.flat(Infinity)) : [start[0], start[1], start[2] || 0, end[0], end[1], end[2] || 0];
        var color_str = item.color || _this.color || '#0080ff';

        // 缓存颜色
        colors[color_str] = colors[color_str] || {
          item: item,
          line_instances: [],
          data: [],
          color: color_str
        };

        // 缓存颜色对应的数据
        colors[color_str].line_instances.push(new _cesium.GeometryInstance({
          geometry: new _cesium.PolylineVolumeGeometry({
            polylinePositions: _cesium.Cartesian3.fromDegreesArrayHeights(positions),
            vertexFormat: _cesium.VertexFormat.DEFAULT,
            shapePositions: computeCircle(radius || 1.0)
          }),
          id: item.id
        }));
        colors[color_str].data.push(item);
      });
      for (var color_str in colors) {
        var _colors$color_str = colors[color_str],
          color = _colors$color_str.color,
          line_instances = _colors$color_str.line_instances,
          startColor = _colors$color_str.startColor,
          endColor = _colors$color_str.endColor,
          _data = _colors$color_str.data;
        // 颜色转换
        var _startColor = startColor || (0, _transformRgb["default"])(color, 0.2);
        var _endColor = endColor || (0, _transformRgb["default"])(color, 1);
        var image = createGradientImage(color_str, _startColor, _endColor);
        var line = new _cesium.Primitive({
          geometryInstances: line_instances,
          show: show,
          appearance: new _cesium.MaterialAppearance({
            flat: false,
            material: new _cesium.Material({
              strict: false,
              fabric: {
                uniforms: {
                  image: image,
                  speed: 5,
                  repeat: new _cesium.Cartesian2(1.0, 0.0) // 设置水平和垂直方向上的重复次数
                },
                source: glsl
              },
              translucent: function translucent() {
                return true;
              },
              minificationFilter: _cesium.TextureMinificationFilter.LINEAR,
              magnificationFilter: _cesium.TextureMagnificationFilter.LINEAR
            })
          }),
          modelMatrix: _cesium.Matrix4.IDENTITY,
          vertexCacheOptimize: false,
          interleave: false,
          compressVertices: true,
          releaseGeometryInstances: true,
          allowPicking: true,
          cull: true,
          asynchronous: true,
          debugShowBoundingVolume: false,
          shadows: _cesium.ShadowMode.DISABLED
        });
        this.setAttribute(line, _data);
        map.scene.primitives.add(line);
        this.primitives.push(line);
      }
    }
  }, {
    key: "setAttribute",
    value: function setAttribute(primitive, data) {
      // 图层标识
      primitive.key = this.key;

      // 数据
      primitive.data = data;

      // 图层名称
      primitive.name = this.name;

      // 标签字段
      primitive.labelField = this.labelField;

      // 模版内容
      primitive.template = this.template;

      // 图例
      primitive.legend = this.legend;

      // 图层控制
      primitive.layerControl = this.layerControl;

      // 取消气泡
      primitive.cancelPopup = this.cancelPopup;

      // 气泡模板
      primitive.tipTemplate = this.tipTemplate;

      // 仅展示
      primitive.viewOnly = this.viewOnly;
    }
  }, {
    key: "destroy",
    value: function destroy() {
      var _this$primitives2;
      var map = this.map;
      if ((_this$primitives2 = this.primitives) !== null && _this$primitives2 !== void 0 && _this$primitives2.length) {
        this.primitives.map(function (primitive) {
          map.scene.primitives.remove(primitive);
        });
        this.primitives = null;
      }
    }
  }]);
}();
var _default = exports["default"] = ThreeLineLayer;
//# sourceMappingURL=ThreeLineLayer.js.map
