/**
 * 三维飞行
 * @param viewer 场景主视图
 * @constructor
 */
function RoamAnalysis(viewer) {
    let _self = this;
    _self.polyline = [];
    _self.start = false;
    _self.stop = null;
    _self.target = null;
    _self.isStop = false;
    _self.isDraw = false;
    _self.viewer = viewer;
    _self.height = 455;
    _self.repeatTime = 5;
    _self.repeatNum = 5;
    _self.drawLayer = new Cesium.PrimitiveCollection();
    _self.drawHelper = new DrawGeometryHelper(viewer);
    _self.viewer.scene.primitives.add(_self.drawLayer);

    /**
     * 绘制折线
     * @param name
     * @constructor
     */
    function DrawPolyLine(name) {
        _self.drawHelper.startDrawingPolyline({
            callback: function (position, state) {
                if (state === "drawClick") {
                    _self.polyline.push(cartesian2LonLat(position.clone()));
                } else if (state === "drawEnd") {
                    let property = setRoamRoad(_self.polyline);
                    addRoamRoad(property);
                    _self.drawHelper.stopDrawing();
                    closeCSS(name);
                }
            }
        });
    }

    /**
     * 加载默认飞行路径
     * @param polygon 飞行路线
     * @returns {Cesium.SampledPositionProperty} 飞行路径
     */
    function setRoamRoad(polygon) {
        _self.start = Cesium.JulianDate.fromDate(new Date());
        let time = _self.start.clone();
        let property = new Cesium.SampledPositionProperty();
        viewer.clock.startTime = _self.start.clone();
        viewer.clock.currentTime = _self.start.clone();
        viewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED; //Loop at the end
        viewer.clock.multiplier = 1;
        viewer.clock.shouldAnimate = false;
        for (let i = 0; i < polygon.length - 1; i++) {
            let startPoint = polygon[i], endPoint = polygon[i + 1];
            for (let j = 0; j <= _self.repeatNum; j++) {
                time = Cesium.JulianDate.addSeconds(time, j * (_self.repeatTime / _self.repeatNum), new Cesium.JulianDate());
                let position = null;
                if (startPoint.length >= 2 && endPoint.length >= 2) {
                    position = Cesium.Cartesian3.fromDegrees(startPoint[0] + j * (endPoint[0] - startPoint[0]) / _self.repeatNum,
                        startPoint[1] + j * (endPoint[1] - startPoint[1]) / _self.repeatNum, _self.height);
                } else {
                    continue;
                }
                property.addSample(time, position);
            }
        }
        _self.stop = time.clone();
        _self.viewer.clock.stopTime = _self.stop.clone();
        setActiveCSS(true);
        return property;
    }

    /**
     * 加载飞行路径
     * @param property
     */
    function addRoamRoad(property) {
        _self.target = _self.viewer.entities.add({
            availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
                start: _self.start,
                stop: _self.stop
            })]),
            position: property,
            orientation: new Cesium.VelocityOrientationProperty(property),
            path: {
                resolution: 2,
                material: new Cesium.PolylineGlowMaterialProperty({
                    glowPower: 0.1,
                    color: Cesium.Color.YELLOW
                }),
                width: 10
            },
            point: {
                pixelSize: 8,
                color: Cesium.Color.WHITE
            }
        });
    }

    /**
     * 平面坐标转经纬度
     * @param cartesian
     * @returns {*[]}
     */
    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];
    }

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

    /**
     * 控制按钮点击
     * @param active
     */
    function setActiveCSS(active) {
        if (active) {
            $('#roam-start').addClass('active');
            $('#roam-pause').addClass('active');
            $('#roam-stop').addClass('active')
        } else {
            $('#roam-start').removeClass('active');
            $('#roam-pause').removeClass('active');
            $('#roam-stop').removeClass('active')
        }
    }

    /**
     * 飞行
     * @param clock
     */
    var setview = function (clock) {
        if (Cesium.JulianDate.lessThanOrEquals(_self.viewer.clock.stopTime, clock._currentTime)) {
            _self.stopRoam();
        }
    };
    /**
     * 开始飞行
     */
    RoamAnalysis.prototype.startRoam = function () {
        if (_self.isStop) {
            _self.viewer.clock.currentTime = _self.viewer.clock.startTime;
            _self.isStop = !_self.isStop;
        }
        _self.viewer.clock.onTick.addEventListener(setview);
        _self.viewer.clock.shouldAnimate = true;
        _self.viewer.trackedEntity = _self.target;
    };
    /**
     * 暂停飞行
     */
    RoamAnalysis.prototype.pauseRoam = function () {
        _self.viewer.clock.shouldAnimate = false;
    };
    /**
     * 停止飞行
     */
    RoamAnalysis.prototype.stopRoam = function () {
        _self.isStop = true;
        _self.viewer.clock.shouldAnimate = false;
        _self.viewer.trackedEntity = null;
        _self.viewer.clock.onTick.removeEventListener(setview);
        closeCSS("roam-start");
    };
    /**
     * 加载默认路径
     */
    RoamAnalysis.prototype.loadDefaultRoamRoad = function () {
        _self.Clean();
        let property = setRoamRoad([[108.95836697787028, 34.21802468408287], [108.95842342171491, 34.221000678126835], [108.96048362968126, 34.22100346102044], [108.96046838017541, 34.21795541744988], [108.95836697787028, 34.21802468408287]]);
        addRoamRoad(property);
    };
    /**
     * 绘制自定义路径
     * @param name
     */
    RoamAnalysis.prototype.drawRoamRoad = function (name) {
        _self.Clean();
        DrawPolyLine(name);
    };
    /**
     * 清除路径飞行
     * @constructor
     */
    RoamAnalysis.prototype.Clean = function () {
        _self.drawHelper.stopDrawing();
        _self.drawLayer.removeAll();
        _self.polyline = [];
        _self.start = false;
        _self.stop = null;
        _self.isStop = false;
        _self.isDraw = false;
        if (_self.target) {
            _self.viewer.entities.remove(_self.target);
            _self.target = null;
        }
        _self.stopRoam();
        setActiveCSS(false);

    };

}