var m_map;
var m_view;
var m_sceneLayer;
var m_zoom;
var dyLayer;
var m_drawtool;
var m_printTool;
var queryExtent;
var xmlQueryExtend;
var layerList;
var symble = [];
var initExtent;
var FullExtent;
var geometryService;
var GraphicsLayer_labelLayer;
var GraphicsLayer_myLayer;
var GraphicsLayer_identityLayer;
var GraphicsLayer_extendLayer;
var GraphicsLayer_fickerLayer;
var GraphicsLayer_DrawLayer;
var GraphicsLayer_flyTipLayer;
var lengthMeasureWidget;
var groundColor = [255, 255, 255];
var currentMapMode;
var currentExtent;
var currentScale;
var cameraList=[];
var highlightSelect;
var highlightSelectExtra;
var totalMapLoadCount=0;
var currentMapLoadCount=0;
var spatialReferenceJson = {
    wkt: 'PROJCS["shanghaicity_chy",GEOGCS["GCS_Beijing_1954",DATUM["D_Beijing_1954",SPHEROID["Krasovsky_1940",6378245.0,298.3]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",-3457147.81],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",121.2751921],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]'
};
var isMapLoaded = false;
var fe0;
var fe1;
var fe2;
var fe3;
var fe4;
var fe5;
var fe6;
var fe7;
var fe8;
var fe9;
var fe10;
var m_sceneLayerViewArr = [];
function init3DScene() {
    currentMapMode = "3D";
    require(["esri/Map", "esri/Graphic", "esri/geometry/Extent", "esri/geometry/Polygon",
            "esri/geometry/Point", "esri/views/MapView", "esri/views/SceneView", "esri/layers/MapImageLayer", "esri/layers/TileLayer", "esri/layers/VectorTileLayer", "esri/layers/GraphicsLayer",
            "esri/tasks/GeometryService", "esri/portal/Portal", "esri/WebScene", "esri/widgets/LayerList","esri/widgets/Legend",
            "esri/widgets/Expand",
            "esri/config", "esri/widgets/ScaleBar", "esri/layers/FeatureLayer", "esri/layers/SceneLayer", "esri/layers/support/LabelClass", "esri/widgets/NavigationToggle", "esri/widgets/Zoom", "esri/widgets/Compass", "esri/Color", "esri/core/watchUtils", "esri/symbols/TextSymbol", "esri/Camera", "dojo/domReady!"],
        function(Map, Graphic, Extent, Polygon, Point, MapView, SceneView, MapImageLayer, TileLayer, VectorTileLayer, GraphicsLayer, GeometryService, Portal, WebScene, LayerList, Legend, Expand,
                 esriConfig, ScaleBar, FeatureLayer, SceneLayer, LabelClass, NavigationToggle, Zoom, Compass, Color, watchUtils, TextSymbol, Camera) {
            m_map = new Map({
                ground: {
                    surfaceColor: groundColor
                }
            });
            dyAddMapLayerByConfig();
            // dyAddCameraListByConfig();
            AddMapGraphicLayers();
            m_view = new SceneView({
                container: "mapDiv",
                constraints: {
                    collision: {
                        enabled: false
                    },
                    tilt: {
                        max:85,
                        min: 0
                    }
                },
                map: m_map,
                viewingMode: "local",
                alphaCompositingEnabled: true,
                environment: {
                    background: {
                        type: "color",
                        color: [255, 255, 255, 1]
                    },
                    starsEnabled: true,
                    atmosphereEnabled: true
                },
                ui: {
                    components: ["attribution"]
                }
            });
            m_view.environment.lighting.date = new Date("August 10, 2020 11:00:00 UTC");
            m_view.environment.lighting.directShadowsEnabled = false;
            AddSceneViewWidget();
            m_view.when(function() {
                //初始化sceneLayerView
                m_view.map.layers.forEach(function(layer, index) {
                    m_view.whenLayerView(layer)
                        .then(function(layerView) {
                            if (layer.type === "scene") {
                                m_sceneLayerViewArr.push(layerView);
                            }
                        }).catch(console.error);
                });
                //初始化视点
                var initCameraJSON=global_config_json.map.initCamera;
                if(initCameraJSON){
                    setCamera(0,initCameraJSON.position[0],initCameraJSON.position[1],initCameraJSON.position[2],initCameraJSON.heading,initCameraJSON.tilt);
                }
                else {
                    var centerPoint = new Point({
                        x: 2514,
                        y: 2169,
                        z: 662,
                        spatialReference: m_view.spatialReference
                    });
                    setCameraBypoint(0, centerPoint, 337, 70, currentScale);
                }
                //onMapLoaded();
                var displaynoneDiv1 = document.getElementsByClassName("esri-attribution__powered-by");
                for (var i = 0; i < displaynoneDiv1.length; i++) {
                    displaynoneDiv1[i].style.display = "none"
                }
                var displaynoneDiv2 = document.getElementsByClassName("esri-widget-button");
                for (var i = 0; i < displaynoneDiv2.length; i++) {
                    displaynoneDiv2[i].style.display = "none"
                }
                m_view.watch("camera", updateIndicator);
                watchUtils.when(m_view, "animation", watchAnimation);
                m_zoom = new Zoom({
                    view: m_view
                });
                if (currentExtent != null) {
                    m_view.extent = currentExtent;
                    setCameraBypoint(1, currentExtent.center, 0, 45, currentScale)
                }
            });
            m_view.on("click",
                function(event) {
                    var screenPoint = {
                        x: event.x,
                        y: event.y
                    };
                    var hitPoint = m_view.toMap(screenPoint);
                    console.log("hitPoint:", hitPoint);
                    m_view.hitTest(screenPoint).then(function(response) {
                        var result = response.results[0];
                        if (result) {
                            var x = result.mapPoint.x;
                            var y = result.mapPoint.y;
                            if (result.graphic) {
                                m_view.whenLayerView(result.graphic.layer).then(function(lyrView) {
                                    if (highlightSelect) {
                                        highlightSelect.remove()
                                    }
                                    highlightSelect = lyrView.highlight(result.graphic);
                                    lyrView.goTo({
                                        target: result.graphic
                                    });
                                })
                            }
                        }
                    });
                });
            function setContentInfo(center, scale, floorNumber) {
                var popupDiv = document.createElement("div");
                popupDiv.setAttribute("style", "height: 400px;width:600px;border: 1px solid #A8A8A8;");
                var layerFloor = new MapImageLayer({
                    url: "http://120.55.160.15:6080/arcgis/rest/services/HKLZM/MapServer",
                    id: "楼层"
                });
                var popupView = new MapView({
                    container: popupDiv,
                    map: new Map({
                        layers: [layerFloor]
                    }),
                    center: new Point({
                        x: 589.976,
                        y: 4146.679
                    }),
                    constraints: {
                        rotationEnabled: false
                    },
                    ui: {
                        components: []
                    }
                });
                popupView.when(function() {
                    popupView.extent = new Extent({
                        xmin: 480,
                        ymin: 4050,
                        xmax: 680,
                        ymax: 4250,
                        spatialReference: popupView.spatialReference
                    });
                    if (floorNumber) {
                        if (floorNumber.length > 0) {
                            var number = parseInt(floorNumber.substr(0, floorNumber.length - 1));
                            if (number > 7) {
                                number = Math.ceil(number / 2)
                            }
                            openLayer(popupView.map, "F" + number)
                        }
                    }
                });
                return popupView.container
            }
            function openLayer(openMap, layerName) {
                var layers = openMap.layers.items[0].allSublayers;
                if (layers.length > 0) {
                    for (var i = 0; i < layers.length; i++) {
                        var layer = layers.items[i];
                        if (layer.title == layerName) {
                            layer.visible = true;
                            if (layer.sublayers) {
                                for (var j = 0; j < layer.sublayers.length; j++) {
                                    layer.sublayers.items[j].visible = true
                                }
                            }
                        } else {
                            if (layer.sublayers) {
                                layer.visible = false
                            }
                        }
                    }
                }
            }
            function updateIndicator(camera) {
                if(m_view.scale<300){
                    m_view.scale=300;
                }
                //console.log("heading:"+camera.heading+",tilt:"+camera.tilt+",positionX:"+camera.position.x+",positionY:"+camera.position.y+",positionZ:"+camera.position.z+",scale:"+m_view.scale);
            }
            function watchAnimation(animation) {
                console.log("animation.state:", animation.state);
                animation.when(function(animation) {
                    console.log("animation:", animation)
                }).
                catch(function(animation) {
                    console.log(animation.state)
                })
            }
            function watchCircle(pointX, pointY, pointZ, headingValue, tiltValue) {
                require(["esri/Camera", "esri/geometry/Point"],
                    function(Camera, Point) {
                        currentCircle = 0;
                        var pt = new Point({
                            x: pointX,
                            y: pointY,
                            z: pointZ,
                            spatialReference: m_view.spatialReference
                        });
                        var cam = new Camera({
                            heading: headingValue,
                            tilt: tiltValue,
                            position: pt
                        });
                        m_view.camera = cam;
                        beginCircle(pointX, pointY, pointZ, currentCircle, tiltValue)
                    })
            }
            var currentCircle = 0;
            isCircle = false;
            function beginCircle(pointX, pointY, pointZ, headingValue, tiltValue) {
                var duringTime = 1e3;
                var R = pointZ * Math.tan(tiltValue * Math.PI / 180);
                var viewX = pointX - R * Math.cos((90 - headingValue) * Math.PI / 180);
                var viewY = pointY - R * Math.sin((90 - headingValue) * Math.PI / 180);
                m_view.goTo({
                        center: [viewX, viewY, pointZ, m_view.spatialReference],
                        heading: headingValue,
                        tilt: tiltValue
                    },
                    {
                        easing: "linear",
                        duration: duringTime
                    }).then(function() {
                    if (isCircle) {
                        if (currentCircle > 360) {
                            currentCircle = 0
                        }
                        if (currentCircle < 0) {
                            currentCircle = 360
                        }
                        currentCircle -= 1;
                        console.log(currentCircle);
                        beginCircle(pointX, pointY, pointZ, currentCircle, tiltValue)
                    }
                })
            }
            function AddSceneViewWidget() {
                // var viewTest = document.getElementById("viewTest");
                // m_view.ui.add(viewTest, "bottom-right")
            }

            function dyAddMapLayerByConfig() {
                var serverUrl = "";
                var serverType = "";
                var serverLabel = "";
                var serverVisible = "";
                //fullextent参数加载
                var extentArray = global_config_json.map.fullextent;
                fullExtent = new Extent(parseFloat(extentArray[0]), parseFloat(extentArray[1]), parseFloat(extentArray[2]), parseFloat(extentArray[3]));
                //geometryservice加载
                serverType = "geometryservice";
                serverUrl = global_config_json.map.geometryservice;
                dyAddMapLayer(serverUrl, serverType, serverLabel, serverVisible)
                //3D,2D地图加载
                var mapJson;
                if(global_config_json.map.maptype == "3D"){
                    mapJson = global_config_json.map.basemaps3D;
                }else{
                    mapJson = global_config_json.map.basemaps;
                }
                totalMapLoadCount = mapJson.length  ;
                for(var i=0;i<mapJson.length;i++) {
                    // loadLayerCount++;
                    serverUrl = mapJson[i].Layer.url;
                    serverType = mapJson[i].Layer.type;
                    serverLabel = mapJson[i].Layer.label;
                    serverVisible = mapJson[i].Layer.visible;
                    dyAddMapLayer(serverUrl, serverType, serverLabel, serverVisible)
                }
            }

            function dyAddMapLayer(serverUrl, serverType, serverLabel, serverVisible) {
                var layer;
                switch (serverType) {
                    case "geometryservice":{
                        geometryService = new GeometryService(serverUrl);
                        break;
                    }
                    case "tiled":{
                        layer = new TileLayer({
                            url: serverUrl,
                            id: serverLabel
                        });
                        layer.visible = serverVisible;
                        layer.when(function () {
                            isCompleteLoadMap();
                        });
                        m_map.add(layer);
                        break;
                    }
                    case "dynamic":{
                        dyLayer = new MapImageLayer({
                            url: serverUrl,
                            id: serverLabel
                        });
                        dyLayer.visible = serverVisible;
                        var currentElevationInfo = {
                            mode: "relative-to-ground",
                            offset: -1,
                            unit: "meters"
                        };
                        dyLayer.elevationInfo = currentElevationInfo;
                        dyLayer.when(function () {
                            isCompleteLoadMap();
                        });
                        m_map.add(dyLayer);
                        break;
                    }
                    case "featurelayer":{
                        if(serverLabel.indexOf("水系")>-1){
                            layer = new FeatureLayer({
                                url:serverUrl,
                                id:serverLabel,
                                renderer: {
                                    type: "simple",
                                    symbol: {
                                        type: "polygon-3d",
                                        symbolLayers: [{
                                            type: "water",
                                            waveDirection: 180,
                                            color: "#b3ccfe",
                                            waveStrength: "moderate",
                                            waterbodySize: "large"
                                        }]
                                    }
                                }
                            });
                        }
                        else{
                            layer = new FeatureLayer({
                                url:serverUrl,
                                id:serverLabel
                            });
                        }
                        layer.when(function () {
                            isCompleteLoadMap();
                        });
                        m_map.add(layer);
                        break;
                    }
                    case "scene":{
                        m_sceneLayer = new SceneLayer({
                            url: serverUrl,
                            id: serverLabel,
                            popupEnabled: true
                        });
                        if(serverLabel.indexOf("建筑物")>0){
                            var locationRenderer = {
                                type: "simple",
                                symbol: {
                                    type: "mesh-3d",
                                    symbolLayers: [{
                                        type: "fill",
                                        material: {
                                            color: [255,255,255,0.9],
                                            colorMixMode: "replace"
                                        },
                                        edges: {
                                            type: "solid",
                                            color: [200, 200, 200, 1],
                                            size: 1
                                        }
                                    }]
                                }
                            };
                            if(serverLabel=="高层建筑物"){
                                var locationRenderer1 = {
                                    type: "unique-value",
                                    // attribute of interest - Earthquake magnitude
                                    //field: "备注",
                                    valueExpression:"When($feature.OBJECTID==8406 || $feature.OBJECTID==120||$feature.OBJECTID==1593,'HIDDEN','SHOW')",
                                    defaultSymbol:{
                                        type: "mesh-3d",
                                        symbolLayers: [{
                                            type: "fill",
                                            material: {
                                                color: [255,255,255,0.9],
                                                colorMixMode: "replace"
                                            },
                                            edges: {
                                                type: "solid",
                                                color: [200, 200, 200, 1],
                                                size: 1
                                            }
                                        }]
                                    },
                                    uniqueValueInfos: [
                                        {
                                            value: "HIDDEN",  // 0 acres
                                            symbol: {
                                                type: "mesh-3d", // autocasts as new MeshSymbol3D()
                                                symbolLayers: [{
                                                    type: "fill", // autocasts as new FillSymbol3DLayer()
                                                    material: {
                                                        color: [0,0,0,0],
                                                        colorMixMode: "replace"
                                                    }
                                                }]
                                            },
                                            label: "fewer than 200,00 acres"
                                        }
                                    ]
                                };
                                m_sceneLayer.renderer = locationRenderer1;
                            }
                            else {
                                m_sceneLayer.renderer = locationRenderer;
                            }

                        }
                        m_sceneLayer.when(function () {
                            isCompleteLoadMap();
                        });
                        m_map.add(m_sceneLayer);
                        break;
                    }
                    case "vector":
                    {
                        var vlayer = new VectorTileLayer({
                            url: serverUrl,
                            id: serverLabel
                        });
                        vlayer.when(function () {
                            isCompleteLoadMap();
                        });
                        m_map.add(vlayer);
                        break;
                    }
                }
            }
            
            function AddMapGraphicLayers() {
                GraphicsLayer_labelLayer = new GraphicsLayer;
                // GraphicsLayer_labelLayer.elevationInfo = {
                //         mode: "relative-to-scene"
                //      };
                // GraphicsLayer_labelLayer.listMode = "hide";
                GraphicsLayer_myLayer = new GraphicsLayer;
                // GraphicsLayer_myLayer.listMode = "hide";
                GraphicsLayer_identityLayer = new GraphicsLayer;
                GraphicsLayer_identityLayer.elevationInfo = {
                    mode: "relative-to-scene"
                };
                // GraphicsLayer_identityLayer.listMode = "hide";
                GraphicsLayer_extendLayer = new GraphicsLayer;
                GraphicsLayer_extendLayer.listMode = "hide";
                GraphicsLayer_fickerLayer = new GraphicsLayer;
                // GraphicsLayer_fickerLayer.listMode = "hide";
                GraphicsLayer_DrawLayer = new GraphicsLayer;
                // GraphicsLayer_DrawLayer.listMode = "hide";
                GraphicsLayer_flyTipLayer = new GraphicsLayer;
                // GraphicsLayer_flyTipLayer.listMode = "hide";
                m_map.add(GraphicsLayer_labelLayer);
                m_map.add(GraphicsLayer_identityLayer);
                m_map.add(GraphicsLayer_extendLayer);
                m_map.add(GraphicsLayer_DrawLayer);
                m_map.add(GraphicsLayer_myLayer);
                m_map.add(GraphicsLayer_flyTipLayer);
                m_map.add(GraphicsLayer_fickerLayer);
                // mapHighlightbymessage(GraphicsLayer_identityLayer);
            }
        })
}

function isCompleteLoadMap() {
    currentMapLoadCount++;
    //console.log("current:"+currentMapLoadCount+"/total:"+totalMapLoadCount);
    if(currentMapLoadCount==totalMapLoadCount){
        onMapLoaded();
    }
}

function GetIFrameInfoWinContent(type, url) {
    var str = " <div style='width:600px;height:500px;'><iframe src='" + url + "' width='100%' height='100%' frameborder='0' scrolling='yes'></iframe></div>";
    return str
}

function goToCamera(CameraJSON) {
    require(["esri/Camera", "esri/geometry/Point"],
        function(Camera, Point) {
            var pt = new Point({
                x: CameraJSON.position[0],
                y: CameraJSON.position[1],
                z: CameraJSON.position[2],
                spatialReference: m_view.spatialReference
            });
                m_view.goTo({
                    target: pt,
                    heading: CameraJSON.heading,
                    tilt: CameraJSON.tilt
                })
        })
}
function setCamera(isAnimation, pointX, pointY, pointZ, headingValue, tiltValue, scaleValue) {
    require(["esri/Camera", "esri/geometry/Point"],
        function(Camera, Point) {
            var pt = new Point({
                x: pointX,
                y: pointY,
                z: pointZ,
                spatialReference: m_view.spatialReference
            });
            if (isAnimation) {
                m_view.goTo({
                    target: pt,
                    heading: headingValue,
                    tilt: tiltValue,
                    scale: scaleValue
                })
            } else {
                var cam = new Camera({
                    heading: headingValue,
                    tilt: tiltValue,
                    position: pt
                });
                m_view.camera = cam
            }
        })
}

function setCameraBypoint(isAnimation, centerPoint, headingValue, tiltValue, scaleValue) {
    require(["esri/Camera", "esri/geometry/Point"],
        function(Camera, Point) {
            var R = centerPoint.z * Math.tan(tiltValue * Math.PI / 180);
            var viewX = centerPoint.x - R * Math.cos((90 - headingValue) * Math.PI / 180);
            var viewY = centerPoint.y - R * Math.sin((90 - headingValue) * Math.PI / 180);
            var viewZ = centerPoint.z;
            console.log("viewX:" + viewX + ",viewY:" + viewY + ",viewZ:" + viewZ);
            if (isAnimation) {
                m_view.goTo({
                    center: [viewX, viewY, viewZ, m_view.spatialReference],
                    heading: headingValue,
                    tilt: tiltValue
                })
            } else {
                var point = new Point({
                    x: viewX,
                    y: viewY,
                    z: viewZ,
                    spatialReference: m_view.spatialReference
                });
                var cam = new Camera({
                    heading: headingValue,
                    tilt: tiltValue,
                    position: point
                });
                m_view.camera = cam
            }
        })
}
function switchTo2DMap() {

    var currentViewPoint=m_view.viewpoint.clone();
    currentViewPoint.camera.tilt=0;
    currentViewPoint.camera.position.x=m_view.extent.center.x;
    currentViewPoint.camera.position.y=m_view.extent.center.y;
    // currentViewPoint.camera.heading=0;

    m_view.goTo(currentViewPoint).then(function (e) {
        currentExtent = m_view.extent;
        currentScale = m_view.scale;
        currentExtent.spatialReference = m_view.spatialReference;
        initMap();
    });
}
function switchTo3DMap() {
    currentExtent = m_view.extent;
    currentScale = m_view.scale;
    currentExtent.spatialReference = m_view.spatialReference;
    init3DScene()
}
function getLayerByLayerId(layerID) {
    for (var i = 0; i < m_map.layers.items.length; i++) {
        if (m_map.layers.items[i].layerId == layerID) {
            return m_map.layers.items[i]
        }
    }
}
function highLightByObjectIDs(objIDArray) {
    m_view.whenLayerView(m_sceneLayer).when(function(lyrView) {
        if (highlightSelect) {
            highlightSelect.remove()
        }
        highlightSelect = lyrView.highlight(objIDArray)
    })
}
function highLightByGeomtry(geometry) {
    require(["esri/tasks/support/Query", "esri/tasks/QueryTask", "esri/core/watchUtils", "esri/geometry/Geometry"],
        function(Query, QueryTask, watchUtils, Geometry) {
            var query = new Query;
            query.geometry = geometry.extent;
            query.spatialRelationship = "intersects";
            query.outFields = ["OBJECTID"];
            m_view.whenLayerView(m_sceneLayer).when(function(lyrView) {
                if (highlightSelect) {
                    highlightSelect.remove()
                }
                var objids = [];
                watchUtils.whenNotOnce(lyrView, "updating").when(function() {
                    lyrView.queryObjectIds(query).when(function(ids) {
                            console.log(ids);
                            objids = ids
                        },
                        function(error) {
                            objids = ids
                        })
                });
                highlightSelect = lyrView.highlight(objids)
            })
        })
}
function hitTest(geomtry) {
    m_view.hitTest(geomtry).when(function(response) {
        var result = response.results[0];
        if (result) {
            var x = result.mapPoint.x;
            var y = result.mapPoint.y;
            if (result.graphic) {
                m_view.whenLayerView(result.graphic.layer).when(function(lyrView) {
                    if (highlightSelect) {
                        highlightSelect.remove()
                    }
                    highlightSelect = lyrView.highlight(result.graphic);
                    m_view.popup.open({
                        title: "Reverse geocode",
                        features: result.graphic,
                        content: "This is a point of interest"
                    })
                })
            }
        }
    })
}

var viewxmax ;
var viewxmin ;
var viewymax ;
var viewymin ;
var x;
var y;
function initMap() {
    currentMapMode = "2D";
    require(["esri/Map", "esri/views/MapView", "esri/layers/MapImageLayer", "esri/layers/TileLayer", "esri/layers/VectorTileLayer","esri/geometry/Geometry", "esri/geometry/Extent",
            "esri/tasks/GeometryService", "esri/layers/GraphicsLayer", "esri/layers/FeatureLayer", "esri/widgets/ScaleBar",
            "esri/WebMap", "esri/geometry/SpatialReference", "esri/Graphic", "esri/views/2d/draw/Draw",
            "esri/geometry/Polygon", "esri/widgets/Zoom", "esri/widgets/Compass", "esri/widgets/LayerList","esri/widgets/Legend",
            "esri/widgets/Expand",
            "esri/geometry/geometryEngine","esri/tasks/QueryTask", "esri/tasks/support/Query",
            "esri/geometry/Point","esri/core/watchUtils","dojo/on"],
        function(Map, MapView, MapImageLayer, TileLayer,VectorTileLayer, Geometry, Extent, GeometryService,
                 GraphicsLayer, FeatureLayer, ScaleBar, WebMap, SpatialReference, Graphic, Draw, Polygon,
                 Zoom, Compass, LayerList, Legend, Expand, geometryEngine,QueryTask,Query,Point,watchUtils,on) {
            m_map = new Map({
                logo:false,
                slider:false
            });
            dyAddMapLayerByConfig();
            AddMapGraphicLayers();

            viewxmax = global_config_json.map.viewxmax;
            viewxmin = global_config_json.map.viewxmin;
            viewymax = global_config_json.map.viewymax;
            viewymin = global_config_json.map.viewymin;

            m_view = new MapView({
                container: "mapDiv",
                map: m_map,
                popup: {
                    dockEnabled: false,
                    dockOptions: {
                        position: "top-right",
                        breakpoint: false
                    }
                }
            });
 m_view.constraints = {
                rotationEnabled: false  // Disables map rotation
            };

            layerList = new LayerList({
                view: m_view
            });
            AddSceneViewWidget();
            m_view.when(function(evt) {

                // m_view.ui.add("info", "top-right");
               //doToolTip();
                doCustomPopUp();
                var displaynoneDiv1 = document.getElementsByClassName("esri-attribution__powered-by");
                for (var i = 0; i < displaynoneDiv1.length; i++) {
                    displaynoneDiv1[i].style.display = "none"
                }
                var displaynoneDiv2 = document.getElementsByClassName("esri-widget-button");
                for (var i = 0; i < displaynoneDiv2.length; i++) {
                    displaynoneDiv2[i].style.display = "none"
                }
                m_zoom = new Zoom({
                    view: m_view
                });
                // m_view.ui.add(m_zoom, {
                //     position: "top-right"
                // });
                m_view.ui.move([ "zoom", m_zoom ], "top-right");
                var m_compass = new Compass({
                    view: m_view
                });
                m_view.ui.add(m_compass, {
                    position: "top-right"
                });
                //m_view.ui.remove('zoom');
                m_view.ui.remove('attribution');
                m_drawtool = new Draw({
                    view: m_view
                })

                var centerx = m_view.center.x;
                var centery = m_view.center.y;
                // m_view.on("resize",function (event) {
                //
                // });
                var infoDiv = document.getElementById("infoDiv");
                m_view.ui.add(
                    new Expand({
                        view: m_view,
                        content: infoDiv,
                        expandIconClass: "esri-icon-layer-list",
                        expanded: true
                    }),
                    "top-right"
                );

                var legend = new Legend({
                    view: m_view,
                    container: "legendDiv",

                });
                m_view.watch("animation", function(response){
                    if(response && response.state === "running"){
                        // console.log("Animation in progress");
                        window.parent.postMessage(
                            {
                                method: "mapAnimationInProgressCallback"
                            },
                            '*'
                        );
                    }

                });
                m_view.on("drag",function (event) {
                    if(event.action == 'end'){
                        // event.startPropagation();
                    }
                    else{
                        // console.log("drag in progress");
                        window.parent.postMessage(
                            {
                                method: "mapDragingCallback"
                            },
                            '*'
                        );
                    }
                });

                // onMapLoadInfo();
                // dyAddMapLayerByConfig();
                // AddMapGraphicLayers();
            });
            var scaleBar = new ScaleBar({
                view: m_view
            });
            // m_view.ui.add(scaleBar, {
            //     position: "bottom-left"
            // });
            if (currentExtent != null) {
                currentExtent.spatialReference = m_view.spatialReference;
                m_view.extent = currentExtent
            }
            function dyAddMapLayerByConfig() {
                var serverUrl = "";
                var serverType = "";
                var serverLabel = "";
                var serverVisible = "";
                //fullextent参数加载
                var extentArray = global_config_json.map.fullextent;
                fullExtent = new Extent(parseFloat(extentArray[0]), parseFloat(extentArray[1]), parseFloat(extentArray[2]), parseFloat(extentArray[3]));
                if (currentExtent == null) currentExtent = fullExtent;
                //geometryservice加载
                serverType = "geometryservice";
                serverUrl = global_config_json.map.geometryservice;
                dyAddMapLayer(serverUrl, serverType, serverLabel, serverVisible)
                //3D,2D地图加载
                var mapJson;
                if(currentMapMode == "3D"){
                    mapJson = global_config_json.map.basemaps3D;
                }else{
                    mapJson = global_config_json.map.basemaps;
                }
                totalMapLoadCount = mapJson.length;
                for(var i=0;i<mapJson.length;i++) {
                    serverUrl = mapJson[i].Layer.url;
                    serverType = mapJson[i].Layer.type;
                    serverLabel = mapJson[i].Layer.label;
                    serverVisible = mapJson[i].Layer.visible;
                    dyAddMapLayer(serverUrl, serverType, serverLabel, serverVisible)
                }
            }
            function dyAddMapLayer(serverUrl, serverType, serverLabel, serverVisible) {
                var layer;
                switch (serverType) {
                    case "geometryservice":
                    {
                        geometryService = new GeometryService(serverUrl);
                        break
                    }
                    case "tiled":
                    {
                        layer = new TileLayer({
                            url: serverUrl,
                            id: serverLabel
                        });
                        layer.visible = serverVisible;
                        layer.when(function () {
                            isCompleteLoadMap();
                        });
                        m_map.add(layer);
                        break;
                    }
                    case "dynamic":
                    {
                        if (serverLabel == "卫监所动态数据") {

                        } else {
                            dyLayer = new MapImageLayer({
                                url: serverUrl,
                                id: serverLabel
                            });
                            dyLayer.visible = serverVisible;
                        }
                        m_map.add(dyLayer);
                        on(dyLayer, "load",
                            function(evt) {
                                dynamicLayerLoaded(evt)
                            });
                        dyLayer.when(function() {
                            var layerInfo = GetDynamicServiceLayer();
                            for (var i = 0; i < layerInfo.length; i++) {
                                GetLayerRestData(i)
                            }
                        });
                        break;
                    }
                    case "featurelayer":
                    {
                        var restUrl = serverUrl + "?f=pjson";
                        var xmlHttpRest = GetXmlHttpObject();
                        xmlHttpRest.open("GET", restUrl, true);
                        xmlHttpRest.send();
                        xmlHttpRest.onreadystatechange = function() {
                            var responseText = xmlHttpRest.responseText;
                            if (xmlHttpRest.readyState == 4) {
                                var LayerJsonData = JSON.parse(responseText);
                                if (LayerJsonData != "") {
                                    var layers = LayerJsonData.layers;
                                    if (layers.length > 0) {
                                        for (var i = 0; i < layers.length; i++) {
                                            if (layers[i].subLayerIds == null) {
                                                var layerId = layers[i].id;
                                                var layername = layers[i].name;
                                                if(layername)
                                                    var dyLayer = new FeatureLayer({
                                                        url: serverUrl+"/"+layerId,
                                                        id: layerId
                                                    });
                                                dyLayer.visible = serverVisible;
                                                // if(layername == "上水井盖")
                                                //     dyLayer.visible = true;
                                                m_map.add(dyLayer);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    }
                    case "vector":
                    {
                        var vlayer = new VectorTileLayer({
                            url: serverUrl,
                            id: serverLabel
                        });
                        m_map.add(vlayer);
                        break;
                    }
                }
            }
            function dynamicLayerLoaded(event) {
                m_view.zoom = 3
                if (currentExtent != null) {
                    currentExtent.spatialReference = m_view.spatialReference;
                    m_view.extent = currentExtent
                }
            }
            function AddMapGraphicLayers() {
                GraphicsLayer_labelLayer = new GraphicsLayer;
                // GraphicsLayer_labelLayer.listMode = "hide";
                GraphicsLayer_myLayer = new GraphicsLayer({id:"myGLayer"});
                // GraphicsLayer_myLayer.listMode = "hide";
                GraphicsLayer_identityLayer = new GraphicsLayer;
                // GraphicsLayer_identityLayer.listMode = "hide";
                GraphicsLayer_extendLayer = new GraphicsLayer;
                GraphicsLayer_extendLayer.listMode = "hide";
                GraphicsLayer_fickerLayer = new GraphicsLayer;
                // GraphicsLayer_fickerLayer.listMode = "hide";
                GraphicsLayer_DrawLayer = new GraphicsLayer({id:"myDrawGLayer"});
                // GraphicsLayer_DrawLayer.listMode = "hide";
                GraphicsLayer_flyTipLayer = new GraphicsLayer;
                // GraphicsLayer_flyTipLayer.listMode = "hide";
                m_map.add(GraphicsLayer_labelLayer);
                m_map.add(GraphicsLayer_identityLayer);
                m_map.add(GraphicsLayer_DrawLayer);
                m_map.add(GraphicsLayer_flyTipLayer);
                m_map.add(GraphicsLayer_myLayer);
                m_map.add(GraphicsLayer_extendLayer);
                m_map.add(GraphicsLayer_fickerLayer);
            }
            function AddSceneViewWidget() {
                var viewTest = document.getElementById("viewTest");
                m_view.ui.add(viewTest, "top-left");
            }
            watchUtils.whenTrue(m_view,"stationary",function(){
                // if (!m_view.center){
                //     console.log("move in progress");
                // }
                if (m_view.center) {
                    // if(isNewDragHandle){
                    //     var test = myNewDragHandle();
                    // }
                    // return;
                    var xmax = m_view.extent.xmax;
                    var xmin = m_view.extent.xmin;
                    var ymax = m_view.extent.ymax;
                    var ymin = m_view.extent.ymin;

                    var extent = m_view.extent;
                    if (ecxtentChanged !== undefined && ecxtentChanged.xmin === extent.xmin && ecxtentChanged.ymin === extent.ymin
                        && ecxtentChanged.xmax === extent.xmax && ecxtentChanged.ymax === extent.ymax)
                        return;

                    var precision = 5000;//可以忽略超出的精度
                    var diff = 0;
                    var hasChanged = false;

                    if(isSetMapZoom){
                        m_maxZoom = m_view.zoom;
                        isSetMapZoom = false;
                    }


                    if (viewxmin - xmin > precision) {
                        hasChanged = true;
                        diff = viewxmin - xmin;
                        xmin += diff;
                        xmax += diff;
                        //如果调整过后最大值超出，则调整回来，并把对应的y值也调整，否则会死循环
                        if (xmax > viewxmax) {
                            diff = xmax - viewxmax;
                            diff = (ymax - ymin) * diff / (xmax - xmin);
                            xmax = viewxmax;
                            ymin += diff / 2;
                            ymax -= diff / 2;
                        }
                    }
                    if (viewymin - ymin > precision) {
                        hasChanged = true;
                        diff = viewymin - ymin;
                        ymin += diff;
                        ymax += diff;
                        //如果调整过后最大值超出，则调整回来，并把对应的x值也调整，否则会死循环
                        if (ymax > viewymax) {
                            diff = ymax - viewymax;
                            diff = (xmax - xmin) * diff / (ymax - ymin);
                            ymax = viewymax;
                            xmin += diff / 2;
                            xmax -= diff / 2;
                        }
                    }
                    if (xmax - viewymax > precision) {
                        hasChanged = true;
                        diff = xmax - viewymax;
                        xmin -= diff;
                        xmax -= diff;
                        //如果调整过后最小值超出，则调整回来，并把对应的y值也调整，否则会死循环
                        if (xmin < viewxmin) {
                            diff = viewxmin - xmin;
                            diff = (ymax - ymin) * diff / (xmax - xmin);
                            xmin = viewxmin;
                            ymin += diff / 2;
                            ymax -= diff / 2;
                        }
                    }
                    if (ymax - viewymax > precision) {
                        hasChanged = true;
                        diff = ymax - viewymax;
                        ymin -= diff;
                        ymax -= diff;
                        //如果调整过后最小值超出，则调整回来，并把对应的x值也调整，否则会死循环
                        if (ymin < viewymin) {
                            diff = viewymin - ymin;
                            diff = (xmax - xmin) * diff / (ymax - ymin);
                            ymin = viewymin;
                            xmin += diff / 2;
                            xmax -= diff / 2;
                        }
                    }
                    if (hasChanged) {
                         ecxtentChanged = extent;
                        m_view.extent = new Extent({
                            xmin: xmin ,
                            ymin: ymin,
                            xmax: xmax,
                            ymax: ymax,
                            spatialReference: m_view.spatialReference
                        });
                        return;
                    }

                    window.parent.postMessage(
                        {
                            method: "resizeCallback"
                        },
                        '*'
                    );

                        x=m_view.center.x;
                        y=m_view.center.y;

                    document.addEventListener("touchstart", function (e) {

                        x=m_view.center.x;
                        y=m_view.center.y;
                        x=x-0;
                        y=y-0;
                    });


                    //监听 touchmove 事件 手指 移动时 做的事情
                    document.addEventListener("touchmove", function (e) {

                        e.preventDefault();
                        // 2 根 手指执行 目标元素放大操作
                        if (e.touches.length >= 2) {
                            x=x-0;
                            y=y-0;
                            m_view.center=new Point({
                                x: x-0,
                                y: y-0,
                                spatialReference: m_view.spatialReference
                            });

                        };
                    });
                    //监听 手指离开屏幕时
                    document.addEventListener("touchend", function (e) {
                    });
                }
            });


        });
}
var ecxtentChanged;
function initMapEdit(){
    require([
        "esri/Map",
        "esri/views/MapView",
        "esri/widgets/Editor",
        "esri/layers/FeatureLayer"
    ], function(Map, MapView, Editor,FeatureLayer) {
        var editConfigCrimeLayer, editConfigPoliceLayer;
        m_map = new Map({
            logo: false
        });
        m_view = new MapView({
            container: "viewDiv",
            map: m_map,
        });
        var serverUrl = GetConfigDataByName("EditLayer") ;
        var xmlHttpRest = GetXmlHttpObject();
        xmlHttpRest.open("GET", serverUrl+ "?f=pjson", true);
        xmlHttpRest.send();
        xmlHttpRest.onreadystatechange = function() {
            var responseText = xmlHttpRest.responseText;
            if (xmlHttpRest.readyState == 4) {
                var LayerJsonData = JSON.parse(responseText);
                if (LayerJsonData != "") {
                    var layers = LayerJsonData.layers;
                    if (layers.length > 0) {
                        for (var i = 0; i < layers.length; i++) {
                            if (layers[i].subLayerIds == null) {
                                var layerId = layers[i].id;
                                var layername = layers[i].name;
                                var dyLayer = new FeatureLayer({
                                    url: serverUrl+"/"+layerId,
                                    id: layername,
                                    title:layername
                                });
                                dyLayer.visible = true;
                                m_map.add(dyLayer);
                            }
                        }
                        m_view.when(function() {
                            function customGroup(grouping){
                                var groupHeading ="";
                                switch (grouping.template.drawingTool) {
                                    case "point":
                                        groupHeading = "点";
                                        break;
                                    case "polyline":
                                        groupHeading = "线";
                                        break;
                                    case "polygon":
                                        groupHeading = "面";
                                        break;
                                }
                                return groupHeading;
                            }

                            var editor = new Editor({
                                view: m_view,
                                supportingWidgetDefaults: {
                                    featureTemplates: {
                                        groupBy: customGroup
                                    }
                                }
                            });
                            // var editor = new Editor({view: m_view});
                            m_view.ui.add(editor, "top-right");
                        });
                    }
                }
            }
        }
    });
}
function GetLayer(layerName) {
    var layer;
    for (var i = 0; i < m_map.layerIds.length; i++) {
        var layeridName = m_map.layerIds[i];
        if (layeridName == layerName) {
            layer = m_map._layers[layeridName];
            return layer
        }
    }
}
function QueryObjectByWhere(LayerName, where, returnFields, KeyValue) {
    KeyValue = KeyValue ? KeyValue: "Query";
    require(["esri/tasks/support/Query", "esri/tasks/QueryTask"],
        function(Query, QueryTask) {
            var query = new Query;
            if (GetConfigDataByName("QueryLayer")) {
                dynamicLayerURL = GetConfigDataByName("QueryLayer")
            }
            var QueryLayerID = GetLayerIdbyName(LayerName);
            if (QueryLayerID == -1) {
                return "无查询图层"
            }
            var queryTask = new QueryTask(dynamicLayerURL + "/" + QueryLayerID);
            queryTask.where = " 1=1 ";
            if (where != "") {
                query.where = where
            }
            query.outSpatialReference = m_map.spatialReference;
            query.returnGeometry = true;
            query.outFields = ["*"];
            if (returnFields != "") {
                query.outFields = returnFields
            }
            queryTask.execute(query,
        function handleQueryResult(results) {
            QueryObjectByWhereCompHandle(results, KeyValue)
        },
        function errorHandler(err) {
            QueryObjectByWhereFaultHandle("查询不成功！", KeyValue)
        })
})
}
function GetLayerIdbyName(name) {
    var layerInfo;
    layerInfo = GetDynamicServiceLayer();
    if (layerInfo != null) {
        for (var j = 0; j < layerInfo.length; j++) {
            var currnetLayer = layerInfo.getItemAt(j);
            if (currnetLayer.title == name) {
                return currnetLayer.id
            }
        }
    }
    return - 1
}
function GetLayerNamebyId(id) {
    var layerInfo;
    layerInfo = GetDynamicServiceLayer();
    if (layerInfo != null) {
        for (var j = 0; j < layerInfo.length; j++) {
            var currnetLayer = layerInfo.getItemAt(j);
            if (currnetLayer.id == id) {
                return currnetLayer.title
            }
        }
    }
    return - 1
}
function GetDynamicServiceLayer() {
    var layerInfo;
    for (var i = 0; i < m_map.layers.length; i++) {
        var BaseLayer = m_map.layers.getItemAt(i);
        if (BaseLayer.declaredClass == "esri.layers.MapImageLayer") {
            layerInfo = m_map.layers.getItemAt(i).sublayers;
            dynamicLayerURL = BaseLayer.url;
            return layerInfo
        } else {}
    }
    return null;
}
function ClearMap() {
    GraphicsLayer_labelLayer.clear();
    GraphicsLayer_myLayer.clear();
    GraphicsLayer_identityLayer.clear();
    GraphicsLayer_extendLayer.clear();
    GraphicsLayer_fickerLayer.clear();
    GraphicsLayer_DrawLayer.clear();
    GraphicsLayer_flyTipLayer.clear()
}
function OpenLayer(layerName, layerVisible) {
    require(["esri/Map", "esri/views/MapView", "esri/layers/MapImageLayer", "dojo/on"],
        function(Map, MapView, MapImageLayer, on) {
            var layer;
            var layerid = GetLayerIdbyName(layerName);
            for (var i = 0; i < m_map.layers.length; i++) {
                var BaseLayer = m_map.layers.getItemAt(i);
                if (BaseLayer.declaredClass == "esri.layers.MapImageLayer") {
                    layer = m_map.layers.getItemAt(i);
                    break;
                }
            }
            layer.visible = layerVisible;
            var sublayer = layer.findSublayerById(parseInt(layerid));
            if(sublayer){
                sublayer.visible = layerVisible;
            }
        })
}
function OpenFeatureLayerByID(layerid, layerVisible) {
    var layer;
    for (var i = 0; i < m_map.layers.length; i++) {
        var BaseLayer = m_map.layers.getItemAt(i);
        if (BaseLayer.declaredClass == "esri.layers.FeatureLayer") {
            layer = m_map.layers.getItemAt(i);
            if (layer.layerId == layerid) {
                layer.visible = layerVisible;
                break
            }
        }
    }
}

function OpenMapImageLayerByName(layerName,layerVisible){
    var layerId = GetFeatureLayerIdbyName(layerName);

    for (var i = 0; i < m_view.allLayerViews.length; i++) {
        var layer = m_view.allLayerViews.getItemAt(i).layer;
        if (layer.id == "动态数据") {
            // layer.allSublayers.items[3].visible = true;
            // break;
            var arr = layer.allSublayers.items;
            for(var j=0;j<arr.length;j++){
                if(arr[j].id==layerId){
                    arr[j].visible = layerVisible;
                    //layer.sublayers.items.push(arr[j]);
                    break;
                }
            }
        }
    }
}

function OpenFeatureLayerByName(layerName, layerVisible) {
    var layerid = "";
    for (var i = 0; i < m_map.layers.length; i++) {
        var BaseLayer = m_map.layers.getItemAt(i);
        if (BaseLayer.declaredClass == "esri.layers.FeatureLayer") {
            layer = m_map.layers.getItemAt(i);
            if (layer.id == layerName) {
                layer.visible = layerVisible;
            }
            // else {
            //     layer.visible = false;
            // }
        }
    }
}
function OpenFeatureLayerByID1(layerid, layerVisible) {
    switch (parseInt(layerid)) {
        case 0:
            fe0.visible = layerVisible;
            if (layerVisible) {
                fe1.visible = false;
                fe2.visible = false;
                fe3.visible = false;
                fe4.visible = false;
                fe5.visible = false;
                fe6.visible = false;
                fe7.visible = false;
                fe8.visible = false;
                fe9.visible = false;
                fe10.visible = false
            }
            break;
        case 1:
            fe1.visible = layerVisible;
            if (layerVisible) {
                fe0.visible = false;
                fe2.visible = false;
                fe3.visible = false;
                fe4.visible = false;
                fe5.visible = false;
                fe6.visible = false;
                fe7.visible = false;
                fe8.visible = false;
                fe9.visible = false;
                fe10.visible = false
            }
            break;
        case 2:
            fe2.visible = layerVisible;
            if (layerVisible) {
                fe0.visible = false;
                fe1.visible = false;
                fe3.visible = false;
                fe4.visible = false;
                fe5.visible = false;
                fe6.visible = false;
                fe7.visible = false;
                fe8.visible = false;
                fe9.visible = false;
                fe10.visible = false
            }
            break;
        case 3:
            fe3.visible = layerVisible;
            if (layerVisible) {
                fe0.visible = false;
                fe1.visible = false;
                fe2.visible = false;
                fe4.visible = false;
                fe5.visible = false;
                fe6.visible = false;
                fe7.visible = false;
                fe8.visible = false;
                fe9.visible = false;
                fe10.visible = false
            }
            break;
        case 4:
            fe4.visible = layerVisible;
            if (layerVisible) {
                fe0.visible = false;
                fe1.visible = false;
                fe2.visible = false;
                fe3.visible = false;
                fe5.visible = false;
                fe6.visible = false;
                fe7.visible = false;
                fe8.visible = false;
                fe9.visible = false;
                fe10.visible = false
            }
            break;
        case 5:
            fe5.visible = layerVisible;
            if (layerVisible) {
                fe0.visible = false;
                fe1.visible = false;
                fe2.visible = false;
                fe3.visible = false;
                fe4.visible = false;
                fe6.visible = false;
                fe7.visible = false;
                fe8.visible = false;
                fe9.visible = false;
                fe10.visible = false
            }
            break;
        case 6:
            fe6.visible = layerVisible;
            if (layerVisible) {
                fe0.visible = false;
                fe1.visible = false;
                fe2.visible = false;
                fe3.visible = false;
                fe4.visible = false;
                fe5.visible = false;
                fe7.visible = false;
                fe8.visible = false;
                fe9.visible = false;
                fe10.visible = false
            }
            break;
        case 7:
            fe7.visible = layerVisible;
            if (layerVisible) {
                fe0.visible = false;
                fe1.visible = false;
                fe2.visible = false;
                fe3.visible = false;
                fe4.visible = false;
                fe5.visible = false;
                fe6.visible = false;
                fe8.visible = false;
                fe9.visible = false;
                fe10.visible = false
            }
            break;
        case 8:
            fe8.visible = layerVisible;
            if (layerVisible) {
                fe0.visible = false;
                fe1.visible = false;
                fe2.visible = false;
                fe3.visible = false;
                fe4.visible = false;
                fe5.visible = false;
                fe6.visible = false;
                fe7.visible = false;
                fe9.visible = false;
                fe10.visible = false
            }
            break;
        case 9:
            fe9.visible = layerVisible;
            if (layerVisible) {
                fe0.visible = false;
                fe1.visible = false;
                fe2.visible = false;
                fe3.visible = false;
                fe4.visible = false;
                fe5.visible = false;
                fe6.visible = false;
                fe7.visible = false;
                fe8.visible = false;
                fe10.visible = false
            }
            break;
        case 10:
            fe10.visible = layerVisible;
            if (layerVisible) {
                fe0.visible = false;
                fe1.visible = false;
                fe2.visible = false;
                fe3.visible = false;
                fe4.visible = false;
                fe5.visible = false;
                fe6.visible = false;
                fe7.visible = false;
                fe8.visible = false;
                fe9.visible = false
            }
            break
    }
}
function buffer(point) {
    require(["esri/tasks/GeometryService", "esri/tasks/support/BufferParameters"],
        function(GeometryService, BufferParameters) {
            var webMerPoint = webMercatorUtils.geographicToWebMercator(point);
            var params = new BufferParameters;
            params.distances = [560];
            params.unit = "kilometers";
            params.geodesic = true;
            params.bufferSpatialReference = new SpatialReference({
                wkid: 3857
            });
            params.outSpatialReference = m_view.spatialReference;
            params.geometries = [webMerPoint];
            geometryService.buffer(params).when(function(results) {
                bufferLayer.add(new Graphic({
                    geometry: results[0]
                }))
            })
        })
}
function bufferPoint(point) {
    if (!bufferEnabled) {
        console.log("buffering not enabled. Hit the space bar key and click/drag to buffer.");
        return
    }
    clearGraphics();
    point.hasZ = false;
    point.z = undefined;
    pointLayer.add(new Graphic({
        geometry: point,
        symbol: pointSym
    }));
    var buffer = geometryEngine.geodesicBuffer(point, 560, "kilometers");
    bufferLayer.add(new Graphic({
        geometry: buffer,
        symbol: polySym
    }))
}
function GetLayerRestData(layerID) {
    var restUrl = dynamicLayerURL + "/" + layerID + "?f=pjson";
    var xmlHttpRest = GetXmlHttpObject();
    xmlHttpRest.open("GET", restUrl, true);
    xmlHttpRest.send();
    xmlHttpRest.onreadystatechange = function() {
        var responseText = xmlHttpRest.responseText;
        if (xmlHttpRest.readyState == 4) {
            symble.push(responseText);
            var layerInfo = GetDynamicServiceLayer();
            if (layerInfo.length - 1 == layerID) {
                isMapLoaded = true;
                onMapLoaded();
            }
        }
    }
}
function GetXmlHttpObject() {
    var xmlHttpRest = null;
    try {
        xmlHttpRest = new XMLHttpRequest
    } catch(e) {
        try {
            xmlHttpRest = new ActiveXObject("Msxml2.XMLHTTP")
        } catch(e) {
            xmlHttpRest = new ActiveXObject("Microsoft.XMLHTTP")
        }
    }
    if (xmlHttpRest == null) {
        return
    }
    return xmlHttpRest
}
function ClearLightLayerStatus() {
    if (highlightSelect) {
        highlightSelect.remove()
    }
    if (highlightSelectExtra) {
        highlightSelectExtra.remove()
    }
}
function flashLayerStatus(featureLayer, statusFieldName, statusValue) {
    require(["esri/tasks/support/Query", "esri/tasks/QueryTask", "esri/core/watchUtils", "esri/geometry/Geometry", "esri/geometry/Polygon"],
        function(Query, QueryTask, watchUtils, Geometry, Polygon) {
            var query = new Query;
            query.where = statusFieldName + "=" + statusValue;
            query.returnGeometry = true;
            query.outFields = ["*"];
            featureLayer.queryFeatures(query).when(function(resultsObjectIDs) {
                m_view.whenLayerView(featureLayer).when(function(lyrView) {
                    if (highlightSelectExtra) {
                        highlightSelectExtra.remove()
                    }
                    highlightSelectExtra = lyrView.highlight(resultsObjectIDs.features)
                });
                console.log("resultsObjectIDs:", resultsObjectIDs)
            })
        })
}
function setCenterExtent(x, y, radius) {
    require(["esri/geometry/Extent"],
        function(Extent) {
            var ext = new Extent({
                xmin: x - radius,
                ymin: y - radius,
                xmax: x + radius,
                ymax: y + radius,
                spatialReference: m_view.spatialReference
            });
            m_view.extent = ext
        })
}
function setExtent(xmin, ymin, xmax, ymax) {
    require(["esri/geometry/Extent"],
        function(Extent) {
            var ext = new Extent({
                xmin: xmin,
                ymin: ymin,
                xmax: xmax,
                ymax: ymax,
                spatialReference: m_view.spatialReference
            });
            m_view.extent = ext
        })
}
function goToPoint(point) {
    if (currentMapMode == "3D") {
        var newCam = m_view.camera.clone();
        newCam.position = point;
        newCam.tilt = 0;
        var ai = m_view.goTo(newCam).when(function(ani) {
            tiltView(45)
        })
    }
}
function tiltView() {
    var tilt = m_view.camera.tilt + .001;
    if (tilt >= 80) {
        tilt = 0
    } else if (tilt >= 40) {
        tilt = 80
    } else {
        tilt = 40
    }
    m_view.goTo({
        tilt: tilt
    })
}

function GetLayerMainRestInfo2(restURL) {
    var restUrl = restURL + "?f=pjson";
    var xmlHttpRest = GetXmlHttpObject();
    xmlHttpRest.open("GET", restUrl, true);
    xmlHttpRest.send();
    xmlHttpRest.onreadystatechange = function() {
        var responseText = xmlHttpRest.responseText;
        if (xmlHttpRest.readyState == 4) {
            GetLayerMainRestInfo_Complete2(restURL, responseText);
        }
    }
}

function GetLayerMainRestInfo_Complete2(restURL, data){
    extraLayerJsonData = JSON.parse(data);
    // onMapLoadInfo();
    // myNewDragHandle();
}

function GetLayerMainRestInfo1(restURL) {
    var restUrl = restURL + "?f=pjson";

    $.ajax({
        type:'get',
        url:restUrl,
        crossDomain:true,
        dataType:'jsonp',
        success:GetLayerMainRestInfo_Complete(restURL,data)
    });
}

function GetLayerMainRestInfo(restURL) {
    var restUrl = restURL + "?f=pjson";
    var xmlHttpRest = GetXmlHttpObject();
    xmlHttpRest.open("GET", restUrl, true);
    xmlHttpRest.send();
    xmlHttpRest.onreadystatechange = function() {
        var responseText = xmlHttpRest.responseText;
        if (xmlHttpRest.readyState == 4) {
            GetLayerMainRestInfo_Complete(restURL, responseText)
        }
    }
}


var extraLayerJsonData;
function GetLayerMainRestInfo_Complete(restURL, data) {
    extraLayerJsonData = JSON.parse(data);
    var layers = extraLayerJsonData.layers;
    require(["esri/layers/FeatureLayer"],
        function(FeatureLayer) {
            if (layers.length > 0) {
                for (var i = 0; i < layers.length; i++) {
                    var fl = new FeatureLayer({
                        url: restURL + "/" + layers[i].id,
                        id: layers[i].name,
                        visible: false
                    });
                    var content = "{*}";
                    var url = "";
                    switch (layers[i].name) {
                        case "一级医疗机构":
                            url = "";
                            content = "机构名称：{COMP_NAME}<br>卫生许可：{HEALTH_LIC}<br>地址：{BUS_ADDR}<br>电话：{TELPHONE}<br><a onclick='showDetail(\"" + layers[i].name + '","' + url + '"' + ",1)'>详细信息</a>";
                            fl.popupTemplate = {
                                title: "一级医疗机构",
                                content: content
                            };
                            break;
                        default:
                            fl.popupTemplate = {
                                title: "详细信息",
                                content: content
                            };
                            break
                    }
                    m_map.add(fl)
                }
            }
        })
}
function showDetail(type, url, id) {
    if (!url) {
        return
    }
    m_view.popup.close();
    var title="详细信息";
    switch(type){
        case "水箱":
            title="国家会展中心二次供水设施每日巡查录入表";
            break;
        case "空气在线监测点":
            title="国家会展中心空气在线监测每日巡查录入表";
            break;
        default:
            title="详细信息";
            break;
    }
    var infoDiv = $("#infoDialog").dialog({
        width: 620,
        height: 550,
        modal: true,
        title:title
    });
    if (infoDiv.length > 0) {
        infoDiv.attr("style", "width:600px;height:500px;");
        infoDiv.html(GetIFrameInfoWinContent(type, url));
        $(".ui-dialog-title").text(title);
    } else {
        alert("未发现详细信息");
    }

}
//
var isSetMapZoom = false;
var m_maxZoom = 1;
//范围四至查询
function queryForExtent(Layername,where,precision){
    var layerId = GetFeatureLayerIdbyName(Layername);
    if (layerId == -1) {
        alert("没有此图层");
        return;
    }
    require([
        "esri/tasks/FindTask",
        "esri/tasks/support/FindParameters",
        "esri/tasks/IdentifyTask",
        "esri/tasks/support/IdentifyParameters",
        "esri/geometry/Point",
        "esri/tasks/QueryTask", "esri/tasks/support/Query",
        "esri/geometry/Extent",
        "esri/Graphic",
        "esri/geometry/geometryEngine",
        "dojo/on",

    ], function (  FindTask, FindParameters, IdentifyTask, IdentifyParameters,Point,
                   QueryTask, Query, Extent, Graphic,geometryEngine, on) {
        // dynamicLayerURL = GetConfigDataByName("QueryLayer")+"/250";

        var queryTask = new QueryTask({
            url: GetConfigDataByName("QueryLayer")+"/" + layerId
        });
        var query = new Query();
        // query.geometry =  geo;
        query.outFields =  ["*"];
        query.returnGeometry = true;
        //query.geometry = option.geometry || null;
        // query.spatialRelationship = "intersects";
        query.where = where ;
        queryTask.execute(query).then(function (results) {
            if(results.features.length >0){
                 viewxmax = results.features[0].geometry.extent.xmax + 0;
                 viewxmin = results.features[0].geometry.extent.xmin - 0;
                 viewymax = results.features[0].geometry.extent.ymax + 0;
                 viewymin = results.features[0].geometry.extent.ymin - 0;
                var extent = new Extent({
                    xmin: results.features[0].geometry.extent.xmin -0,
                    ymin: results.features[0].geometry.extent.ymin -0,
                    xmax: results.features[0].geometry.extent.xmax -0,
                    ymax: results.features[0].geometry.extent.ymax -0,
                    spatialReference: m_view.spatialReference
                });
                var point = new Point({
                    x: results.features[0].geometry.extent.center.x-0,
                    y: results.features[0].geometry.extent.center.y-0,
                    spatialReference: m_view.spatialReference});
                // m_view.extent = extent;
                m_view.goTo({
                    target: point,
                    zoom: 8
                }).then(function (ani) {
                    // alert("goT");
                });
                isSetMapZoom = true;
            }

        });
    });
}

//点生产buffer
function getBufferByPoint(x,y,radius,layername,m_showGraphic,isGoTo){
    var buffer;
    require([
        "esri/geometry/Point",
        "esri/geometry/geometryEngine",
        "esri/geometry/Circle"
    ], function ( Point,geometryEngine,Circle) {
        var point = new Point({
            x: x-0,
            y: y-0,
            spatialReference: m_view.spatialReference});
        // buffer =  geometryEngine.buffer(point, radius-0, "meters");
        buffer =  new Circle({
            radius:radius,
            radiusUnit:"meters",
            center:{ x: x-0,
                y: y-0,
                spatialReference: m_view.spatialReference}
        });
        newQuerybyWhereStr("", layername,GetConfigDataByName("MYQueryLayer"),buffer,m_showGraphic,isGoTo);
    });
    // return buffer;
}
//得到grid的geometry
function getGridGeometryByGridID(gridid,Layername){
    var gridgeo
    require([
        "esri/tasks/FindTask",
        "esri/tasks/support/FindParameters",
        "esri/tasks/IdentifyTask",
        "esri/tasks/support/IdentifyParameters",
        "esri/geometry/Point",
        "esri/tasks/QueryTask", "esri/tasks/support/Query",
        "esri/geometry/Extent",
        "esri/Graphic",
        "esri/geometry/geometryEngine",
        "dojo/on",

    ], function (  FindTask, FindParameters, IdentifyTask, IdentifyParameters,Point,
                   QueryTask, Query, Extent, Graphic,geometryEngine, on) {
        // dynamicLayerURL = GetConfigDataByName("QueryLayer")+"/250";

        var queryTask = new QueryTask({
            url: GetConfigDataByName("QueryLayer")+"/250"
        });
        var query = new Query();
        query.geometry =  null;
        query.outFields =  ["*"];
        query.returnGeometry = true;
        //query.geometry = option.geometry || null;
        query.spatialRelationship = "intersects";
        query.where = " 网格编码='"+gridid+"'";
        queryTask.execute(query).then(function (results) {
            if(results.features.length >0){
                gridgeo = results.features[0].geometry;
                //queryByGeometryAndLayer(gridgeo,Layername);
                newQuerybyWhereStr("", Layername,GetConfigDataByName("MYQueryLayer"),gridgeo);
            }
        });
    });
}

// 网格编码查询
function identifyTask(point,callbackfun) {
    require([
        "esri/tasks/FindTask",
        "esri/tasks/support/FindParameters",
        "esri/tasks/IdentifyTask",
        "esri/tasks/support/IdentifyParameters",
        "esri/geometry/Point",
        "esri/tasks/QueryTask", "esri/tasks/support/Query",
        "esri/geometry/Extent",
        "esri/Graphic",
        "esri/geometry/geometryEngine",
        "dojo/on"

    ], function (  FindTask, FindParameters, IdentifyTask, IdentifyParameters,Point,
                   QueryTask, Query, Extent, Graphic,geometryEngine, on) {
            // dynamicLayerURL = GetConfigDataByName("QueryLayer")+"/250";

        var queryTask = new QueryTask({
            url: GetConfigDataByName("QueryLayer")+"/250"
        });
        var query = new Query();
        query.geometry =  null;
        query.outFields =  ["*"];
        query.returnGeometry = true;
        //query.geometry = option.geometry || null;
        query.spatialRelationship = "intersects";
        query.where = "1=1";

        query.geometry  = new Point({
                x: point.split(',')[0]-0,
                y: point.split(',')[1]-0,
                spatialReference: m_view.spatialReference});
        queryTask.execute(query).then(function (results) {
            if(results.features.length >0)
                callbackfun(results.features[0].attributes["网格编码"]);
            else{
                callbackfun("error");
            }
        });
     });
}
//空间查询展示
function showQueryResult(idResults) {
    // //创建线符号
    // var lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASH, new dojo.Color([255, 100, 100]), 3);
    // //创建面符号
    // var fill = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, lineSymbol,new dojo.Color([0, 0, 0]), 0);
alert(2)
    if (idResults.length > 0) {
        var htmls = "<table style=\"width: 100%\">";
        htmls = htmls + "<tr bgcolor=\"#E0E0E0\"><td> 图层 </td><td> 名 称</td></tr>";
        for (var i = 0; i < idResults.length; i++) {
            var result = idResults[i];
            //获得图形graphic
            var graphic = result.feature;
            //设置图形的符号
            // graphic.setSymbol(lineSymbol );
            var namevalue = result.feature.attributes.Name;
            console.log(namevalue)
            if (i % 2 == 1) {
                htmls = htmls + "<tr  bgcolor=\"#E0E0E0\"><td>" +
                    result.layerName + "</td>" +
                    // "<td>" + namevalue + "</td>" +
                    "</tr>";
            }
            else {
                htmls = htmls + "<tr><td>" + result.layerName + "</td><td>"
                    + namevalue + "</td></tr>";
            }

            map.graphics.add(graphic);
        }
        htmls = htmls + "</table>";
        document.getElementById("divShowResult").innerHTML = htmls;
        $("#divShowResult").show();
    }
    else {
        document.getElementById("divShowResult").innerHTML = "";
        $("#divShowResult").show();
    }
}

// new拖拽地图handle
var isNewDragHandle = false;
function myNewDragHandle(){
    var draghandle
    require(["esri/core/watchUtils"],
        function( watchUtils) {
            draghandle = watchUtils.whenTrue(m_view,"drag",function(event){
                if(event.action == 'end'){
                }
                else{
                    var xmax = m_view.extent.xmax;
                    var xmin = m_view.extent.xmin;
                    var ymax = m_view.extent.ymax;
                    var ymin = m_view.extent.ymin;
                    var precision = 70;
                    var hasChanged = false;
                    if (viewxmin - xmin > precision) {hasChanged=true;}
                    if (viewymin - ymin > precision) {hasChanged=true;}
                    if (xmax - viewymax > precision) {hasChanged=true;}
                    if (ymax - viewymax > precision) {hasChanged=true;}
                    if(hasChanged){
                        event.stopPropagation();
                        isNewDragHandle = true;
                    }
                }
            });
        });
    return draghandle;
}

function addFeaturelayerAndRendererByName(layername,renderer,labelingInfo,id,definitionExpression,featureReduction,visible){
    var layerId = GetFeatureLayerIdbyName(layername);
    // showLoadingDiv("测试。。。");
    if (layerId == -1) {
        alert("没有此图层");
        return;
    }
    if(visible == undefined)
        visible = false;
    var serverUrl = GetConfigDataByName("extraFeatureServerURL");
    var dyLayer;
    console.log(serverUrl);
    require([ "esri/layers/FeatureLayer", "dojo/_base/array", "dojo/dom"],
        function( FeatureLayer, arrayUtils, dom) {
            dyLayer = new FeatureLayer({
                url: serverUrl+"/"+layerId,
                id: id,
                outFields: ["*"],
                visible:visible,
                // elevationInfo: {
                //     // elevation mode that will place points on top of the buildings or other SceneLayer 3D objects
                //     mode: "relative-to-scene"
                // },
                // featureReduction: {
                //     type: "selection"
                // }
                featureReduction : featureReduction
            });
            // console.log(dyLayer);

            dyLayer.renderer = renderer;
            if(labelingInfo != undefined){
                dyLayer.labelingInfo = labelingInfo;
            }
            if(definitionExpression != undefined){
                dyLayer.definitionExpression = definitionExpression;
            }
            // if(featureReduction != undefined){
            //     dyLayer.featureReduction = featureReduction;
            // }
            m_map.add(dyLayer);


            // dyLayer.load().then(function() {
            //     // table is loaded. ready to be queried.
            //     removeLoadingDiv();
            // });

            mapHighlightbymessage(dyLayer);
            // m_view.whenLayerView(dyLayer).then(function(layerView){
            // });

            m_view.whenLayerView(dyLayer).then(function(layerView){
                layerView.watch("updating", function(value){
                    // availableFields will become available
                    // once the layer view finishes updating
                    if((dyLayer.id == "bulidingdetaillayer"||dyLayer.id ==  "123456layer" )){
                     
                        if (value) {
                        }
                        else{
                            removeLoadingDiv();
                        }
                        return;
                    }

                });
            });
        });

}

function addFeaturelayerAndRendererByNameRoad(layerId,renderer,labelingInfo,id,definitionExpression,featureReduction,visible,elevationInfo){
    if(visible == undefined)
        visible = false;
    var serverUrl = GetConfigDataByName("roadServiceURL")+"/" + layerId;
    var dyLayer;
    // console.log(serverUrl);
    require([ "esri/layers/FeatureLayer", "dojo/_base/array", "dojo/dom"],
        function( FeatureLayer, arrayUtils, dom) {
            dyLayer = new FeatureLayer({
                url: serverUrl,
                id: id,
                outFields: ["*"],
                visible:visible,
                opacity:0.8
                // elevationInfo: {
                //     // elevation mode that will place points on top of the buildings or other SceneLayer 3D objects
                //     mode: "relative-to-scene"
                // },
                // featureReduction: {
                //     type: "selection"
                // }
            });
            //console.log(dyLayer);
            if(renderer != undefined)
                dyLayer.renderer = renderer;
            if(labelingInfo != undefined){
                dyLayer.labelingInfo = labelingInfo;
            }
            if(definitionExpression != undefined){
                dyLayer.definitionExpression = definitionExpression;
            }
            if(featureReduction != undefined){
                dyLayer.featureReduction = featureReduction;
            }
            if(elevationInfo != undefined){
                dyLayer.elevationInfo = elevationInfo;
            }
            m_map.add(dyLayer);


            // dyLayer.load().then(function() {
            //     // table is loaded. ready to be queried.
            //     removeLoadingDiv();
            // });

            mapHighlightbymessage(dyLayer);
            // m_view.whenLayerView(dyLayer).then(function(layerView){
            // });

            m_view.whenLayerView(dyLayer).then(function(layerView){
                layerView.watch("updating", function(value){
                    // availableFields will become available
                    // once the layer view finishes updating
                    if(!(dyLayer.id == "bulidingdetaillayer"  )){
                        return;
                    }
                    if (value) {
                    }
                    else{
                        removeLoadingDiv();
                    }
                });
            });
        });

}
function dyAddCameraListByConfig(){
    var cameraXml = global_config_json.map.cameras;

    /*var cameraNodes = cameraXml[0].childNodes;
    for (var i = 0; i < cameraNodes.length; i++) {
        var nodeObj = cameraNodes[i];
        if(nodeObj.nodeType==1){

            var tagName = xmlUtil.getNodeTagName(nodeObj);
            var value = xmlUtil.getNodeValue(nodeObj);
            if (tagName == "camera"){
                cameraList.push(JSON.parse(value));
            }
        }

    }*/
}

function addFeatureLayer(serviceURL,layeridArray) {
    require(["esri/layers/FeatureLayer"], function(FeatureLayer) {
        $(layeridArray).each(function (index,id) {
            var layer= new FeatureLayer({
                // URL to the service
                url: serviceURL+"/"+id,
                opacity:0.8
            });

            if(parseInt(id)>=19){
                var currentElevationInfo1 = {
                    mode: "relative-to-ground",
                    offset: 15,
                    unit: "meters"
                };
                layer.elevationInfo = currentElevationInfo1;
                if(parseInt(id)>=24){
                    layer.visible=false;
                }
            }

            m_map.add(layer);
        });

    });
}

function AddFeatureLayerByData(layerDataArray,renderer,labelingInfo,id,fields,clusterConfig) {
    require(["esri/layers/FeatureLayer","esri/layers/support/Field","esri/renderers/HeatmapRenderer","esri/Graphic"], function(FeatureLayer,Field,HeatmapRenderer,Graphic) {
        var graphics = [];
        // var fields = [{
        //     name: "OBJECTID",
        //     alias: "OBJECTID",
        //     type: "oid"
        // },{name: "菜场数量",alias:"菜场数量",type: "text"}
        // ];
        for(var i=0;i<layerDataArray.length;i++){
            var geometry;
            var attribute;
            if(layerDataArray[i].geometry){
                geometry = layerDataArray[i].geometry;
            }
            else{
                geometry = {
                    type: "point",  // autocasts as new Point()
                    x: parseFloat(layerDataArray[i].住址x),
                    y: parseFloat(layerDataArray[i].住址y),
                    spatialReference:m_view.spatialReference
                };
            }
            if(layerDataArray[i].attributes)
                attribute = layerDataArray[i].attributes;
            else
                attribute = layerDataArray[i];
            var g1=new Graphic({
                geometry: geometry,
                attributes: attribute
            });
            graphics.push(g1);
        }
        var geometryType = "point";
        if(layerDataArray[0].geometry ){
            geometryType = layerDataArray[0].geometry.type;
        }
        var layer = new FeatureLayer({
            geometryType:geometryType,
            objectIdField:"OBJECTID",
            source: graphics,
            fields: fields,
            renderer:renderer,
            labelingInfo:labelingInfo,
            id:id,
            outFields: ["*"],
            spatialReference:m_view.spatialReference
        });

        // if(clusterConfig != undefined)
        //     layer.featureReduction = clusterConfig ;
        m_view.map.add(layer);
    });
}

