/**
 * 缓冲区分析
 * @param viewer 场景主视图
 * @constructor
 */
function BufferAnalysis(viewer) {
    let _self = this;
    _self.polygon = [];
    _self.polyline = [];
    _self.raidus = null;
    _self.viewer = viewer;
    _self.drawLayer = new Cesium.PrimitiveCollection();
    _self.bufferLayer = new Cesium.GeoJsonDataSource('buffer');
    _self.drawHelper = new DrawGeometryHelper(viewer);
    _self.viewer.dataSources.add(_self.bufferLayer);
    _self.viewer.scene.primitives.add(_self.drawLayer);

    /**
     * 绘制点
     * @param name
     * @constructor
     */
    function DrawPoint(name) {
        _self.drawHelper.startDrawingMarker({
            callback: function (position) {
                var billboards = new Cesium.BillboardCollection();
                billboards.add({
                    show: true,
                    position: position,
                    pixelOffset: new Cesium.Cartesian2(0, 0),
                    eyeOffset: new Cesium.Cartesian3(0.0, 0.0, -30.0),
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    width: 6,
                    height: 6,
                    image: "data:image/svg+xml,<svg t=\"1537323945478\" class=\"icon\" style=\"\" viewBox=\"0 0 1024 1024\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" p-id=\"1087\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"1024\" height=\"1024\"><defs><style type=\"text/css\"></style></defs><path d=\"M512 599.9c-90.4 0-164-73.6-164-164s73.6-164 164-164 164 73.6 164 164-73.5 164-164 164z m0-252.3c-48.7 0-88.3 39.6-88.3 88.3s39.6 88.3 88.3 88.3 88.3-39.6 88.3-88.3-39.6-88.3-88.3-88.3z\" fill=\"#29CCB6\" p-id=\"1088\"></path><path d=\"M512 991c-11.9 0-23.7-4.2-33.3-12.5-37.9-33.2-370.6-330.6-370.6-542.6 0-222.7 181.2-403.8 403.8-403.8s403.8 181.1 403.8 403.8c0 211.9-332.6 509.4-370.6 542.6-9.3 8.3-21.2 12.5-33.1 12.5z m0-858c-167 0-302.9 135.9-302.9 302.9 0 115.2 173.8 316.3 302.8 436.5 107.7-100.9 303-309.9 303-436.5 0-167-135.8-302.9-302.9-302.9z\" fill=\"#4585F5\" p-id=\"1089\"></path></svg>",//'./Build/Cesium/ThirdParty/Draw/img/glyphicons_242_google_maps.png',
                    color: new Cesium.Color(1.0, 1.0, 1.0, 1.0),
                    sizeInMeters: true
                });
                _self.drawLayer.add(billboards);
                var point = turf.point(cartesian2LonLat(position));
                var buffered = turf.buffer(point, 0.00001 * _self.raidus, {units: 'kilometers'});
                _self.bufferLayer.load(buffered, {
                    fill: Cesium.Color.fromAlpha(Cesium.Color.AQUA, 0.3),
                    clampToGround: true
                });
                closeCSS(name);

            }
        })
    }

    /**
     * 绘制线
     * @param name
     * @constructor
     */
    function DrawPolyLine(name) {
        _self.drawHelper.startDrawingPolyline({
            callback: function (position, state) {
                if (state === "drawClick") {
                    _self.polyline.push(position);
                } else if (state === "drawEnd") {
                    var primitive = new Cesium.GroundPrimitive({
                        geometryInstances: new Cesium.GeometryInstance({
                            geometry: new Cesium.CorridorGeometry({
                                vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
                                positions: _self.polyline,
                                width: 1
                            }),
                            attributes: {
                                color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromAlpha(Cesium.Color.RED, 1))
                            }
                        }),
                        appearance: new Cesium.PerInstanceColorAppearance({
                            translucent: true,
                            closed: true,
                            aboveGround: true
                        }),
                        classificationType: Cesium.ClassificationType.BOTH
                    });
                    let p = [];
                    for (let i = 0; i < _self.polyline.length; i++) {
                        p.push(cartesian2LonLat(_self.polyline[i]));
                    }
                    let line = turf.linestring(p);
                    let buffered = turf.buffer(line, 0.00001 * _self.raidus, {units: 'kilometers'});
                    _self.bufferLayer.load(buffered, {
                        fill: Cesium.Color.fromAlpha(Cesium.Color.AQUA, 0.3),
                        clampToGround: true
                    });
                    _self.polyline = [];
                    _self.drawLayer.add(primitive);
                    closeCSS(name);
                }
            }
        });
    }

    /**
     * 绘制面
     * @param name
     * @constructor
     */
    function DrawPolygon(name) {
        _self.drawHelper.startDrawingPolygon({
            callback: function (position, state) {
                _self.polygon.push(position);
                if (state === "drawEnd") {
                    var primitive = new Cesium.GroundPrimitive({
                        id: "polygon",
                        geometryInstances: new Cesium.GeometryInstance({
                            geometry: Cesium.PolygonGeometry.fromPositions({
                                positions: _self.polygon,
                                vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
                            }),
                            attributes: {
                                color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromAlpha(Cesium.Color.RED, 0.6)),//color  必须设置 不然没有效果
                            }
                        }),
                        appearance: new Cesium.PerInstanceColorAppearance({
                            translucent: false,
                            closed: true,
                            aboveGround: true
                        }),
                        geodesic: true,
                        granularity: 10000,
                    });
                    let p = [];
                    for (let i = 0; i < _self.polygon.length; i++) {
                        p.push(cartesian2LonLat(_self.polygon[i]));
                    }
                    p.push(cartesian2LonLat(_self.polygon[0]));
                    let line = turf.polygon([p]);
                    let buffered = turf.buffer(line, 0.00001 * _self.raidus, {units: 'kilometers'});
                    _self.bufferLayer.load(buffered, {
                        fill: Cesium.Color.fromAlpha(Cesium.Color.AQUA, 0.3),
                        clampToGround: true
                    });
                    _self.polygon = [];
                    _self.drawLayer.add(primitive);
                    closeCSS(name);
                }
            },
        });
    }

    /**
     * 平面坐标转经纬度坐标
     * @param cartesian 平面坐标
     * @returns {经度，纬度，高度} EPSG:4326
     */
    function cartesian2LonLat(cartesian) {
        var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        var lon = Cesium.Math.toDegrees(cartographic.longitude);
        var lat = Cesium.Math.toDegrees(cartographic.latitude);
        return [lon, lat, height];
    }

    /**
     * 关闭对应css
     * @param name
     */
    function closeCSS(name) {
        $(('#' + name + "-svg")).css('fill', '#ffffff');
        $('.buffer').removeClass('buffer');
    }

    /**
     * 设置缓冲半径
     * @param radius
     */
    BufferAnalysis.prototype.setBufferRadius = function (radius) {
        _self.raidus = radius;
    };
    /**
     * 点缓冲
     * @param name
     * @constructor
     */
    BufferAnalysis.prototype.PointBuffer = function (name) {
        _self.Clean();
        DrawPoint(name);
    };
    /**
     * 线缓冲
     * @param name
     * @constructor
     */
    BufferAnalysis.prototype.PolylineBuffer = function (name) {
        _self.Clean();
        DrawPolyLine(name);
    };
    /**
     * 面缓冲
     * @param name
     * @constructor
     */
    BufferAnalysis.prototype.PolygonBuffer = function (name) {
        _self.Clean();
        DrawPolygon(name);
    };
    /**
     * 清除缓冲区分析结果
     * @constructor
     */
    BufferAnalysis.prototype.Clean = function () {
        _self.drawHelper.stopDrawing();
        _self.polygon = [];
        _self.polyline = [];
        _self.drawLayer.removeAll();
        _self.bufferLayer.entities.removeAll();

    };

}


