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_areaNameLayer;
var GraphicsLayer_identityLayer;
var GraphicsLayer_extendLayer;
var GraphicsLayer_fickerLayer;
var GraphicsLayer_DrawLayer;
var GraphicsLayer_flyTipLayer;
var lengthMeasureWidget;
var groundColor = [0, 0, 0];
var currentMapMode;
var currentExtent;
var currentScale;
var highlightSelect;
var highlightSelectExtra;
//2020 2 hm
var m_mapClickdraw = false;
var m_mapAttribute = '{ "ID": "1","名称": "测试点1" }';
var m_mapToolTip = '测试点1';
var m_mapImgUrl = 'https://static.arcgis.com/images/Symbols/Shapes/BlackStarLargeB.png';
var m_mapImgWidth = '32px';
var m_mapImgHeight = '32px';
var m_mapAddress;
var m_maphitPoint;
var m_resizetime = null;
var isInLightArea = "";//判断区域高亮移出移入
var isInDrawLayer = "";//判断DrawLayer移出移入
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;
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/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, esriConfig, ScaleBar, FeatureLayer, SceneLayer, LabelClass, NavigationToggle, Zoom, Compass, Color, watchUtils, TextSymbol, Camera) {
            // esriConfig.request.corsEnabledServers.push("http://10.101.35.46");
           
            m_map = new Map({
                ground: {
                    surfaceColor: groundColor
                }
            });
            dyAddMapLayerByConfig();
            // AddMapGraphicLayers();
            m_view = new SceneView({
                container: "mapDiv",
                constraints: {
                    collision: {
                        enabled: false
                    },
                    tilt: {
                        max: 179.99,
                        min: 0
                    }
                },
                map: m_map,
                viewingMode: "local",
                alphaCompositingEnabled: true,
                environment: {
                    background: {
                        type: "color",
                        color: [0, 0, 0, 1]
                    },
                    starsEnabled: false,
                    atmosphereEnabled: false
                },
                ui: {
                    components: ["attribution"]
                }
            });
            AddSceneViewWidget();
            m_view.when(function () {
                var centerPoint = new Point({
                    x: 43184,
                    y: -37270,
                    z: 2e3,
                    spatialReference: m_view.spatialReference
                });
                setCameraBypoint(0, centerPoint, 45, 45, currentScale);
                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
                });
                m_view.ui.add(m_zoom, {
                    position: "top-right"
                });
                var m_navigateToggle = new NavigationToggle({
                    view: m_view
                });
                m_view.ui.add(m_navigateToggle, {
                    position: "top-right"
                });
                var m_compass = new Compass({
                    view: m_view
                });
                m_view.ui.add(m_compass, {
                    position: "top-right"
                });
                m_view.ui.add("info", "top-right");
                if (currentExtent != null) {
                    m_view.extent = currentExtent;
                    setCameraBypoint(1, currentExtent.center, 0, 45, currentScale)
                }
                setTimeout("onMapLoadInfo()",1000);
            });
            m_view.on("pointer-move", function (event) {

                m_view.hitTest(event, GraphicsLayer).then(getGraphics);
                function getGraphics(response) {
                    if (response.results.length) {
                        var result = response.results[0];
                        if (result.graphic) {
                            m_view.whenLayerView(result.graphic.layer).then(function (layerView) {
                                if (highlightSelect) {
                                     try{
                                            highlightSelect.remove();
                                        }catch (e){ }
                                }
                                try{
                                    highlightSelect = layerView.highlight(result.graphic);
                                }catch (e){ }


                                if (result.graphic.attributes && result.graphic.layer.id == "myGLayer") {
                                    if (isInDrawLayer != "") {
                                        postToParentPageMethed("moveOutDrawLayerReturn", [isInDrawLayer]);
                                        isInDrawLayer = "";
                                    }
                                    if (isInLightArea == "") {
                                        isInLightArea = result.graphic.attributes;
                                        postToParentPageMethed("moveInLightAreaReturn", [isInLightArea]);
                                    } else {
                                        if (isInLightArea.OBJECTID != result.graphic.attributes.OBJECTID) {
                                            postToParentPageMethed("moveOutLightAreaReturn", [isInLightArea]);
                                            isInLightArea = result.graphic.attributes;
                                            postToParentPageMethed("moveInLightAreaReturn", [isInLightArea]);
                                        }
                                    }
                                } else if (result.graphic.attributes && result.graphic.layer.id == "myDrawGLayer") {

                                    if (isInDrawLayer == "") {
                                        isInDrawLayer = result.graphic.attributes;
                                        postToParentPageMethed("moveInDrawLayerReturn", [isInDrawLayer]);
                                    } else {
                                        if (isInDrawLayer != result.graphic.attributes) {
                                            postToParentPageMethed("moveOutDrawLayerReturn", [isInDrawLayer]);
                                            isInDrawLayer = result.graphic.attributes;
                                            postToParentPageMethed("moveInDrawLayerReturn", [isInDrawLayer]);
                                        }
                                    }
                                } else {
                                    if (isInLightArea != "") {
                                        postToParentPageMethed("moveOutLightAreaReturn", [isInLightArea]);
                                        isInLightArea = "";
                                    }
                                    if (isInDrawLayer != "") {
                                        postToParentPageMethed("moveOutDrawLayerReturn", [isInDrawLayer]);
                                        isInDrawLayer = "";
                                    }
                                }
                            });

                        }
                    } else {
                        // if(highlightSelect){
                        //     highlightSelect.remove();
                        // }
                        if (isInLightArea != "") {
                            postToParentPageMethed("moveOutLightAreaReturn", [isInLightArea]);
                            isInLightArea = "";
                        }
                        if (isInDrawLayer != "") {
                            postToParentPageMethed("moveOutDrawLayerReturn", [isInDrawLayer]);
                            isInDrawLayer = "";
                        }
                    }
                }
            });

            m_view.on("click", function (event) {
                popupCloseAll("viewClick");

                m_view.hitTest(event).then(function (response) {
                    if (response.results.length) {
                        var result = response.results[0];
                        if (result.graphic) {
                            m_view.whenLayerView(result.graphic.layer).then(function (layerView) {
                                if (highlightSelect) {
                                    try{
                                            highlightSelect.remove();
                                        }catch (e){ }
                                }

                                try{
                                    highlightSelect = layerView.highlight(result.graphic);
                                }catch (e){ }
                            })
                             
                            switch (result.graphic.layer.id) {
                                case "WZXYFeature":{
                                    var jsonStr=result.graphic.attributes;
                                    jsonStr.x=result.graphic.geometry.extent.center.x;
                                    jsonStr.y=result.graphic.geometry.extent.center.y;
                                    postToParentPageMethed("clickWZXYFeatureReturn", [jsonStr]);

                                    break;
                                }
                                case "myDrawGLayer":

                                    var returnList = []
                                    var graphicList = GraphicsLayer_DrawLayer.graphics.items;
                                    for (var i = 0; i < graphicList.length; i++) {
                                        if (result.graphic.geometry.x == graphicList[i].geometry.x && result.graphic.geometry.y == graphicList[i].geometry.y) {
                                            if (graphicList[i].attributes) {
                                                returnList.push(graphicList[i].attributes);
                                            }

                                        }
                                    }

                                    postToParentPageMethed("clickDrawLayerReturn", [returnList]);
                                    break;
                                case "myGLayer":
                                {


                                    //  m_view.goTo(result.graphic)
                                    postToParentPageMethed("clickLightAreaReturn", [result.graphic.attributes]);

                                    break;
                                }
                                default:
                                {
                                    if (result.graphic.layer.declaredClass == "esri.layers.FeatureLayer") {
                                        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 = result.graphic.geometry;
                                        queryTask.execute(query).then(function (results1) {
                                            if (results1.features.length > 0) {
                                            }
                                            // window.parent.postMessage(
                                            //     {
                                            //         method: "mapOnclickCallback",
                                            //         data:[JSON.stringify(result.graphic.attributes).replace(/\"/g,'"'),
                                            //             JSON.stringify(results1.features[0].attributes["网格编码"]).replace(/\"/g,'"')
                                            //         ]
                                            //     },
                                            //     '*'
                                            // );
                                            else {
                                                // window.parent.postMessage(
                                                //     {
                                                //         method: "mapOnclickCallback",
                                                //         data:[JSON.stringify(result.graphic.attributes).replace(/\"/g,'"'),'']
                                                //     },
                                                //     '*'
                                                // );
                                            }
                                        });
                                    }
                                    break;
                                }
                            }

                        }
                    }
                });
            });
            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) {
            }

            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;
                GetConfigData();
                var mapXml = xmlDoc.getElementsByTagName("map");
                var mapNodes = mapXml[0].childNodes;
                for (var i = 0; i < mapNodes.length; i++) {
                    var nodeObj = mapNodes[i];
                    if (nodeObj.nodeType == 1) {
                        var tagName = xmlUtil.getNodeTagName(nodeObj);
                        var value = xmlUtil.getNodeValue(nodeObj);
                        if (tagName == "geometryservice") {
                            serverType = "geometryservice";
                            serverUrl = value;
                            dyAddMapLayer(serverUrl, serverType, serverLabel, serverVisible)
                        } else if (tagName == "fullextent") {
                            var extentArray = value.split(",");
                            fullExtent = new Extent(parseFloat(extentArray[0]), parseFloat(extentArray[1]), parseFloat(extentArray[2]), parseFloat(extentArray[3]))
                        } else {
                            if (tagName == "basemaps" && currentMapMode == "2D") {
                                var childNodes = nodeObj.childNodes;
                                for (var j = 0; j < childNodes.length; j++) {
                                    var childNode = childNodes[j];
                                    if (childNode.nodeType == 1) {
                                        for (var k = 0; k < childNode.attributes.length; k++) {
                                            var attribute = childNode.attributes[k];
                                            var attributeName = attribute.name;
                                            if (attributeName == "label") {
                                                serverLabel = attribute.value
                                            }
                                            if (attributeName == "type") {
                                                serverType = attribute.value
                                            }
                                            if (attributeName == "visible") {
                                                if (attribute.value == "false") serverVisible = false;
                                                else serverVisible = true
                                            }
                                        }
                                        serverUrl = xmlUtil.getNodeValue(childNode);
                                        dyAddMapLayer(serverUrl, serverType, serverLabel, serverVisible)
                                    }
                                }
                            }
                            if (tagName == "basemaps3D" && currentMapMode == "3D") {
                                var childNodes = nodeObj.childNodes;
                                for (var j = 0; j < childNodes.length; j++) {
                                    var childNode = childNodes[j];
                                    if (childNode.nodeType == 1) {
                                        for (var k = 0; k < childNode.attributes.length; k++) {
                                            var attribute = childNode.attributes[k];
                                            var attributeName = attribute.name;
                                            if (attributeName == "label") {
                                                serverLabel = attribute.value
                                            }
                                            if (attributeName == "type") {
                                                serverType = attribute.value
                                            }
                                            if (attributeName == "visible") {
                                                if (attribute.value == "false") serverVisible = false;
                                                else serverVisible = true
                                            }
                                        }
                                        serverUrl = xmlUtil.getNodeValue(childNode);
                                        dyAddMapLayer(serverUrl, serverType, serverLabel, serverVisible)
                                    }
                                }
                            }
                        }
                    }
                }
            }

            function dyAddMapLayer(serverUrl, serverType, serverLabel, serverVisible) {
                var layer;
                switch (serverType) {
                    case "geometryservice":
                    {
                        geometryService = new GeometryService(serverUrl);
                        break
                    }
                    case "tiled":
                    {
                        // if (currentMapMode == "2D") {
                            layer = new TileLayer({
                                url: serverUrl,
                                id: serverLabel
                            });
                            layer.visible = serverVisible;
                            m_map.add(layer)
                        // }
                        break
                    }
                    case "dynamic":
                    {
                        AddMapGraphicLayers();
                        dyLayer = new MapImageLayer({
                            url: serverUrl,
                            id: serverLabel
                        });
                        dyLayer.visible = serverVisible;
                        var currentElevationInfo = {
                            mode: "relative-to-ground",
                            offset: -1,
                            unit: "meters"
                        };
                        dyLayer.elevationInfo = currentElevationInfo;
                        m_map.add(dyLayer);
                        break
                    }
                    case "density":
                    {
                        dyLayer = new MapImageLayer({
                            url: serverUrl,
                            id: serverLabel
                        });
                        dyLayer.visible = serverVisible;
                        m_map.add(dyLayer);
                        break;
                    }
                    case "featurelayer":
                    {
                        m_map.add(layer);
                        break;
                    }
                    case "scene":
                    {
                        m_sceneLayer = new SceneLayer({
                            url: serverUrl,
                            id: serverLabel,
                            popupEnabled: true
                        });
                        var locationRenderer = {
                            type: "simple",
                            symbol: {
                                type: "mesh-3d",
                                symbolLayers: [{
                                    type: "fill",
                                    material: {
                                        color: [120,120,120,0.6],
                                        colorMixMode: "replace"
                                    },
                                    edges: {
                                        type: "solid",
                                        color: [27, 68, 130, .6],
                                        size: 1.5
                                    }
                                }]
                            }
                        };
                        m_sceneLayer.renderer = locationRenderer;
                        m_map.add(m_sceneLayer);
                        break
                    }
                    case "vector":
                    {
                        var vlayer = new VectorTileLayer({
                            url: serverUrl,
                            id: serverLabel
                        });
                        m_map.add(vlayer);
                        break
                    }
                }
            }

            function AddMapGraphicLayers() {
                GraphicsLayer_labelLayer = new GraphicsLayer;
                GraphicsLayer_labelLayer.listMode = "hide";
                GraphicsLayer_myLayer = new GraphicsLayer({id: "myGLayer"});
                GraphicsLayer_myLayer.listMode = "hide";

                GraphicsLayer_areaNameLayer = new GraphicsLayer;
                GraphicsLayer_areaNameLayer.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_areaNameLayer);
                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)
            }
        })
}
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 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() {
    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].id == layerID) {
            return m_map.layers.items[i]
        }
    }
}
function getSubLayerIdbyName(layer, name) {

    var items = layer.allSublayers.items;
    for (var j = 0; j < items.length; j++) {
        var currnetLayer = items[j];
        if (currnetLayer.title == name) {
            return currnetLayer.id
        }
    }

    return -1
}
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/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/geometry/geometryEngine", "esri/tasks/QueryTask", "esri/tasks/support/Query",
            "esri/geometry/Point", "esri/core/watchUtils", "esri/config", "dojo/on"],
        function (Map, MapView, MapImageLayer, TileLayer, Geometry, Extent, GeometryService,
                  GraphicsLayer, FeatureLayer, ScaleBar, WebMap, SpatialReference, Graphic, Draw, Polygon,
                  Zoom, Compass, LayerList, geometryEngine, QueryTask, Query, Point, watchUtils, esriConfig, on) {
            esriConfig.fontsUrl = "https://10.101.35.50/fonts";
            m_map = new Map({
                logo: false,
                slider: false
            });
            dyAddMapLayerByConfig();

            // AddMapGraphicLayers();放到动态图层加载前

            viewxmax = xmlDoc.getElementsByTagName("viewxmax")[0].innerHTML;
            viewxmin = xmlDoc.getElementsByTagName("viewxmin")[0].innerHTML;
            viewymax = xmlDoc.getElementsByTagName("viewymax")[0].innerHTML;
            viewymin = xmlDoc.getElementsByTagName("viewymin")[0].innerHTML;

            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
            };
            m_zoom = new Zoom({
                view: m_view
            });
            // m_view.ui.add(m_zoom, {
            //     position: "top-right"
            // });
            layerList = new LayerList({
                view: m_view
            });

            AddSceneViewWidget();

            m_view.when(function (evt) {
                createInfoDiv();
                // m_view.ui.add("info", "top-right");
                //doToolTip();
                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"
                // });
                var m_compass = new Compass({
                    view: m_view
                });
                // m_view.ui.add(m_compass, {
                //     position: "top-left"
                // });
                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) {
                //
                // });
                m_view.watch("animation", function (response) {
                    if (response && response.state === "running") {
                        // console.log("Animation in progress");
                        // window.parent.postMessage(
                        //     {
                        //         method: "mapAnimationInProgressCallback"
                        //     },
                        //     '*'
                        // );
                    }
                    // else{
                    //     console.log("No animation");
                    // }
                });
                m_view.on("drag", function (event) {
                    if (event.action == 'end') {
                        // event.startPropagation();
                    }
                    else {
                        // console.log("drag in progress");
                        sjDraging = true;
                        window.parent.postMessage(
                            {
                                method: "mapDragingCallback"
                            },
                            '*'
                        );
                    }
                });
                m_view.on("pointer-move", function (event) {

                    m_view.hitTest(event, GraphicsLayer).then(getGraphics);
                    function getGraphics(response) {
                        if (response.results.length) {
                            var result = response.results[0];
                            if (result.graphic) {
                                m_view.whenLayerView(result.graphic.layer).then(function (layerView) {
                                    if (highlightSelect) {
                                        try{
                                            highlightSelect.remove();
                                        }catch (e){ }
                                    }
                                    try{
                                        highlightSelect = layerView.highlight(result.graphic);
                                    }catch (e){ }


                                    if (result.graphic.attributes && result.graphic.layer.id == "myGLayer") {
                                        if (isInDrawLayer != "") {
                                            postToParentPageMethed("moveOutDrawLayerReturn", [isInDrawLayer]);
                                            isInDrawLayer = "";
                                        }
                                        if (isInLightArea == "") {
                                            isInLightArea = result.graphic.attributes;
                                            postToParentPageMethed("moveInLightAreaReturn", [isInLightArea]);
                                        } else {
                                            if (isInLightArea.OBJECTID != result.graphic.attributes.OBJECTID) {
                                                postToParentPageMethed("moveOutLightAreaReturn", [isInLightArea]);
                                                isInLightArea = result.graphic.attributes;
                                                postToParentPageMethed("moveInLightAreaReturn", [isInLightArea]);
                                            }
                                        }
                                    } else if (result.graphic.attributes && result.graphic.layer.id == "myDrawGLayer") {

                                        if (isInDrawLayer == "") {
                                            isInDrawLayer = result.graphic.attributes;
                                            postToParentPageMethed("moveInDrawLayerReturn", [isInDrawLayer]);
                                        } else {
                                            if (isInDrawLayer != result.graphic.attributes) {
                                                postToParentPageMethed("moveOutDrawLayerReturn", [isInDrawLayer]);
                                                isInDrawLayer = result.graphic.attributes;
                                                postToParentPageMethed("moveInDrawLayerReturn", [isInDrawLayer]);
                                            }
                                        }
                                    } else {
                                        if (isInLightArea != "") {
                                            postToParentPageMethed("moveOutLightAreaReturn", [isInLightArea]);
                                            isInLightArea = "";
                                        }
                                        if (isInDrawLayer != "") {
                                            postToParentPageMethed("moveOutDrawLayerReturn", [isInDrawLayer]);
                                            isInDrawLayer = "";
                                        }
                                    }
                                });

                            }
                        } else {
                            // if(highlightSelect){
                            //     highlightSelect.remove();
                            // }
                            if (isInLightArea != "") {
                                postToParentPageMethed("moveOutLightAreaReturn", [isInLightArea]);
                                isInLightArea = "";
                            }
                            if (isInDrawLayer != "") {
                                postToParentPageMethed("moveOutDrawLayerReturn", [isInDrawLayer]);
                                isInDrawLayer = "";
                            }
                        }
                    }
                });

                m_view.on("click", function (event) {
                    popupCloseAll("viewClick");
                  
                    // if(m_mapClickdraw){
                    //     var screenPoint = {
                    //         x: event.x,
                    //         y: event.y
                    //     };
                    //     GraphicsLayer_DrawLayer.removeAll();
                    //     var hitPoint = m_view.toMap(screenPoint);
                    //     m_maphitPoint = hitPoint;
                    //     var point = hitPoint.x+","+hitPoint.y;
                    //     var jsonStr = '{"ExChangeRoot": {"Features": [' +
                    //         ' { "type": "point", "featureName": "兴趣点", "Feature":[ { "Geometry": { "Points":[ { "Point": "'+point+'" } ]},' +
                    //         '"Attribute": '+m_mapAttribute+', "ToolTip": "'+m_mapToolTip+'",' +
                    //         '"ImgUrl":"'+m_mapImgUrl +'" ,"ImgWidth":"'+ m_mapImgWidth +'","ImgHeight":"'+m_mapImgHeight +'" } ] } ]}}';
                    //     doGetGraphicByJson(jsonStr,false);
                    //     m_mapClickdraw = false;
                    //     // var url = GetConfigDataByName("WebServiceExtraURL");
                    //     // WsCommonClass("GetAddress",["x","y"],[hitPoint.x,hitPoint.y],mapClickdrawCallback,null,url);
                    //     GetAddressByXY(hitPoint.x,hitPoint.y,50);
                    //     function mapClickdrawCallback(evt){
                    //         if(evt[0] == null) {
                    //             window.parent.postMessage(
                    //                 {
                    //                     method: "clicklocationcallbackfun",
                    //                     data: []
                    //                 },
                    //                 '*'
                    //             );
                    //             return;
                    //         }
                    //         m_mapAddress = evt[0].textContent;
                    //         var url = GetConfigDataByName("WebServiceConvertCoordinateURL");
                    //         WsCommonClass("ConvertXYToLonLat",["lon","lat"],[m_maphitPoint.x,m_maphitPoint.y],mapClickdrawCallback1,null,url);
                    //     }
                    //     function mapClickdrawCallback1(evt){
                    //         if(evt[0] == null) {
                    //             console.log("");
                    //             return;
                    //         }
                    //         var point = evt[0].textContent;
                    //         window.parent.postMessage(
                    //             {
                    //                 method: "clicklocationcallbackfun",
                    //                 data: [point,m_mapAddress]
                    //             },
                    //             '*'
                    //         );
                    //     }
                    // }
                    m_view.hitTest(event).then(function (response) {
                        if (response.results.length) {
                            var result = response.results[0];
                            if (result.graphic) {
                                m_view.whenLayerView(result.graphic.layer).then(function (layerView) {
                                    if (highlightSelect) {
                                        try{
                                            highlightSelect.remove();
                                        }catch (e){ }
                                    }

                                    try{
                                        highlightSelect = layerView.highlight(result.graphic);
                                    }catch (e){ }
                                })
                                switch (result.graphic.layer.id) {
                                    case "WZXYFeature":{
                                         var jsonStr=result.graphic.attributes;
                                        jsonStr.x=result.graphic.geometry.extent.center.x;
                                        jsonStr.y=result.graphic.geometry.extent.center.y;
                                        postToParentPageMethed("clickWZXYFeatureReturn", [jsonStr]);
                                        
                                        break;
                                    }
                                    case "myDrawGLayer":

                                        var returnList = []
                                        var graphicList = GraphicsLayer_DrawLayer.graphics.items;
                                        for (var i = 0; i < graphicList.length; i++) {
                                            if (result.graphic.geometry.x == graphicList[i].geometry.x && result.graphic.geometry.y == graphicList[i].geometry.y) {
                                                if (graphicList[i].attributes) {
                                                    returnList.push(graphicList[i].attributes);
                                                }

                                            }
                                        }

                                        postToParentPageMethed("clickDrawLayerReturn", [returnList]);
                                        break;
                                    case "myGLayer":
                                    {


                                              //  m_view.goTo(result.graphic)
                                                postToParentPageMethed("clickLightAreaReturn", [result.graphic.attributes]);

                                        break;
                                    }
                                    default:
                                    {
                                        if (result.graphic.layer.declaredClass == "esri.layers.FeatureLayer") {
                                            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 = result.graphic.geometry;
                                            queryTask.execute(query).then(function (results1) {
                                                if (results1.features.length > 0) {
                                                }
                                                // window.parent.postMessage(
                                                //     {
                                                //         method: "mapOnclickCallback",
                                                //         data:[JSON.stringify(result.graphic.attributes).replace(/\"/g,'"'),
                                                //             JSON.stringify(results1.features[0].attributes["网格编码"]).replace(/\"/g,'"')
                                                //         ]
                                                //     },
                                                //     '*'
                                                // );
                                                else {
                                                    // window.parent.postMessage(
                                                    //     {
                                                    //         method: "mapOnclickCallback",
                                                    //         data:[JSON.stringify(result.graphic.attributes).replace(/\"/g,'"'),'']
                                                    //     },
                                                    //     '*'
                                                    // );
                                                }
                                            });
                                        }
                                        break;
                                    }
                                }

                            }
                        }
                    });
                });
                m_view.watch("scale", function (event) {
                    if (m_view.zoom % 1 === 0) {  //整数 
                        //chartLayer点放大缩小
                        if (chartLayer) {

                            var imgsize = chartLayerSize - (chartLayerSize * (12 - m_view.zoom) * 0.05);//zoom每级差5%
                            var list = chartLayer.chartOption.series;
                            for (var i = 0; i < list.length; i++) {
                                list[i].effect.symbolSize = imgsize
                            }
                            var option = {
                                series: list
                            };
                            chartLayer.setChartOption(option);
                        }
                        //GraphicsLayer_DrawLayer点放大缩小
                        var DrawLayerGraphics = GraphicsLayer_DrawLayer.graphics;
                        if (DrawLayerGraphics.length > 0) {
                            if (imgSizeList == []) {
                                return;
                            }
                            for (var i = 0; i < DrawLayerGraphics.length; i++) {
                                if (DrawLayerGraphics.items[i].symbol.type == "picture-marker") {
                                    if(DrawLayerGraphics.items[i].attributes.newImgWidth){
                                        var width=DrawLayerGraphics.items[i].attributes.newImgWidth;
                                        var height=DrawLayerGraphics.items[i].attributes.newImgHeight;
                                        var newImgWidth = width - (width * (14 - m_view.zoom) * 0.05);//zoom每级差5%
                                        var newImgHeight = height - (height * (14 - m_view.zoom) * 0.05)
                                        var symbol = {
                                            type: "picture-marker",
                                            url: DrawLayerGraphics.items[i].symbol.url,
                                            width: newImgWidth + "px",
                                            height: newImgHeight + "px"
                                        }
                                        DrawLayerGraphics.items[i].symbol = symbol
                                    }

                                }

                            }
                        }

                    }
                });

                setTimeout("onMapLoadInfo()",1000);
                // dyAddMapLayerByConfig();
                // AddMapGraphicLayers();
            });
            var scaleBar = new ScaleBar({
                view: m_view
            });
            // m_view.ui.add(scaleBar, {
            //     position: "bottom-left"
            // });
            if (currentExtent != null) {
                m_view.extent = currentExtent
            }
            function dyAddMapLayerByConfig() {
                var serverUrl;
                var serverType;
                var serverLabel;
                var serverVisible;
                GetConfigData();
                var mapXml = xmlDoc.getElementsByTagName("map");
                var mapNodes = mapXml[0].childNodes;
                for (var i = 0; i < mapNodes.length; i++) {
                    var nodeObj = mapNodes[i];
                    if (nodeObj.nodeType == 1) {
                        var tagName = xmlUtil.getNodeTagName(nodeObj);
                        var value = xmlUtil.getNodeValue(nodeObj);
                        if (tagName == "geometryservice") {
                            serverType = "geometryservice";
                            serverUrl = value;
                            dyAddMapLayer(serverUrl, serverType, serverLabel, serverVisible)
                        } else if (tagName == "fullextent") {
                            var extentArray = value.split(",");
                            fullExtent = new Extent(parseFloat(extentArray[0]), parseFloat(extentArray[1]), parseFloat(extentArray[2]), parseFloat(extentArray[3]))
                        } else if (tagName == "basemaps") {
                            var childNodes = nodeObj.childNodes;
                            for (var j = 0; j < childNodes.length; j++) {
                                var childNode = childNodes[j];
                                if (childNode.nodeType == 1) {
                                    for (var k = 0; k < childNode.attributes.length; k++) {
                                        var attribute = childNode.attributes[k];
                                        var attributeName = attribute.name;
                                        if (attributeName == "label") {
                                            serverLabel = attribute.value
                                        }
                                        if (attributeName == "type") {
                                            serverType = attribute.value
                                        }
                                        if (attributeName == "visible") {
                                            if (attribute.value == "false") serverVisible = false;
                                            else serverVisible = true
                                        }
                                    }
                                    serverUrl = xmlUtil.getNodeValue(childNode);
                                    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;
                        m_map.add(layer);
                        break;
                    }
                    case "dynamic":
                    {
                        AddMapGraphicLayers()
                        if (serverLabel == "卫监所动态数据") {
                            layer = new MapImageLayer({
                                url: serverUrl,
                                sublayers: [{
                                    id: 0,
                                    popupTemplate: {
                                        title: "{COUNTY}",
                                        content: "{POP2007} people lived in this county in 2007"
                                    }
                                },
                                    {
                                        id: 1,
                                        popupTemplate: {
                                            title: "{COUNTY}",
                                            content: "{POP2007} people lived in this county in 2007"
                                        }
                                    }]
                            });
                        } 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 "density":
                    {
                        dyLayer = new MapImageLayer({
                            url: serverUrl,
                            id: serverLabel
                        });
                        dyLayer.visible = serverVisible;
                        m_map.add(dyLayer);
                        dyLayer.on("layerview-create", function(event){ 
                            createWZXYFeature();
                        });
                       

                        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
            }

            function AddMapGraphicLayers() {
                // debugger;
                GraphicsLayer_labelLayer = new GraphicsLayer;
                GraphicsLayer_labelLayer.listMode = "hide";
                GraphicsLayer_myLayer = new GraphicsLayer({id: "myGLayer"});
                GraphicsLayer_myLayer.listMode = "hide";
                GraphicsLayer_areaNameLayer = new GraphicsLayer();
                GraphicsLayer_areaNameLayer.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_myLayer);
                m_map.add(GraphicsLayer_areaNameLayer);
                m_map.add(GraphicsLayer_labelLayer);
                m_map.add(GraphicsLayer_identityLayer);
                m_map.add(GraphicsLayer_extendLayer);
                m_map.add(GraphicsLayer_flyTipLayer);
                m_map.add(GraphicsLayer_fickerLayer);
                m_map.add(GraphicsLayer_DrawLayer);
            }

            function AddSceneViewWidget() {
                // var viewTest = document.getElementById("viewTest");
                // m_view.ui.add(viewTest, "bottom-right")
            }

            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 - viewxmax > 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"
                        },
                        '*'
                    );
                    if (sjDraging) {
                        sjDraging = false;
                        if (m_resizetime) {
                            clearTimeout(m_resizetime);
                        }
                        m_resizetime = setTimeout(function () {
                            // 执行地图中心点查询地址 or 地图中心点查询查询部件
                            // sj_type  0 关闭   1 地址   2 部件  3 地址和部件
                            sj_mapResize();
                        }, 300);
                    }

                    // 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 url = GetConfigDataByName("EditLayer")+"/0";
        // var featurelayer = new FeatureLayer({
        //     url:url,
        //     title:"房屋"
        // });
        // m_map.add(featurelayer);
        // var url1 = GetConfigDataByName("EditLayer")+"/1";
        // var featurelayer1 = new FeatureLayer({
        //     url:url1,
        //     title:"土地"
        // });
        // featurelayer1.visible = true;
        // m_map.add(featurelayer);
        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" && BaseLayer.id == "动态数据") {

            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();
    if (chartLayer) {
        chartLayer.removeLayer();
        chartLayer = null;
    }
    if (chartLayer2) {
        chartLayer2.removeLayer();
        chartLayer2 = null;
    }
    if (chartLayer3) {
        chartLayer3.removeLayer();
        chartLayer3 = null;
    }
}
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
                }
            }
            var sublayer = layer.findSublayerById(parseInt(layerid));
            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 closeMapImageLayerByName() {
    var layer = getLayerByLayerId("density_1");

    var items = layer.allSublayers.items;
    for (var i = 0; i < items.length; i++) {
        if (items[i].sublayers == null) {
            items[i].visible = false;
        }
    }
}
// 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();

    var restUrl1 = GetConfigDataByName("MYQXFeatureLayer") + "?f=pjson";
    var xmlHttpRest1 = GetXmlHttpObject();
    xmlHttpRest1.open("GET", restUrl1, true);
    xmlHttpRest1.send();
    xmlHttpRest1.onreadystatechange = function () {
        var responseText = xmlHttpRest1.responseText;
        if (xmlHttpRest1.readyState == 4) {
            GetLayerMainRestInfo_Complete3("", responseText);
        }
    }
}
var qxLayerJsonData;
function GetLayerMainRestInfo_Complete3(restURL, data) {
    qxLayerJsonData = 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;
                        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;
                        case "三级医疗机构":
                            url = "http://10.101.35.25:8080/wjsite/a/tWd3MedicalLicense/medicalDtails?id=cb885991548744a7aa02febd425d977d";
                            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;
                        case "空调机房":
                            url = "";
                            content = "描述：{描述}";
                            fl.popupTemplate = {
                                title: "空调机房",
                                content: content
                            };
                            break;
                        case "宾馆":
                            url = "";
                            content = "名称：{COMP_NAME}<br>地址：{BUS_ADDR}<br>卫生许可：{HEALTH_LIC}<br>联系方式：{TELPHONE}<br><a onclick='showDetail(\"" + layers[i].name + '","' + url + '"' + ",1)'>详细信息</a>";
                            fl.popupTemplate = {
                                title: "宾馆",
                                content: content
                            };
                            break;
                        case "重大活动保障医疗机构":
                            url = "";
                            content = "单位名称：{单位名称}<br>地址：{一户一档地址}<br><a onclick='showDetail(\"" + layers[i].name + '","' + url + '"' + ",1)'>详细信息</a>";
                            fl.popupTemplate = {
                                title: "重大活动保障医疗机构",
                                content: content
                            };
                            break;
                        case "监督机构":
                            url = "";
                            content = "名称：{区县名称}<br>地址：{地址}<br>电话：{电话}<br><a onclick='showDetail(\"" + layers[i].name + '","' + url + '"' + ",1)'>详细信息</a>";
                            fl.popupTemplate = {
                                title: "监督机构",
                                content: content
                            };
                            break;
                        case "管网水监测点":
                            url = "http://10.101.35.25:8088/#/?isMap=true&type=testResultsTable&id=60000000000";
                            var url2 = "http://10.101.35.25:8088/#/?isMap=true&type=patrolRecordsTable&id=60000000000";
                            content = "监测点编号：{JCDCODE}<br>监测点位置：{JCDADDR}<br>" +
                                "<a onclick='showDetail(\"" + layers[i].name + '","' + url + '"' + ",1)'>检验结果</a>&nbsp;&nbsp;" +
                                "<a onclick='showDetail(\"" + layers[i].name + '","' + url2 + '"' + ",1)'>监督员巡查</a>";
                            fl.popupTemplate = {
                                title: "管网水监测点",
                                content: content
                            };
                            break;
                        case "主要接待场所":
                            url = "http://10.101.35.25:8080/wjsite/a/document/obj/publicPlaceDtails?id={ID}";
                            var url2 = "http://10.101.35.25:8088/#/?isMap=true&type=ggcsWaterForm&id={ID}";
                            var url3 = "http://10.101.35.25:8088/#/?isMap=true&type=ggcsSampingTable&id={ID}";
                            var url4 = "http://10.101.35.25:8088/#/?isMap=true&type=waterSupplyCheckTable&code=00&id={ID}";
                            content = "名称：{COMP_NAME}<br>地址：{BUS_ADDR}<br>卫生许可：{HEALTH_LIC}<br>联系方式：{TELPHONE}<br>" +
                                "<a onclick='showDetail(\"" + layers[i].name + '","' + url + '"' + ",1)'>档案信息</a>&nbsp;&nbsp;" +
                                "<a onclick='showDetail(\"" + layers[i].name + '","' + url2 + '"' + ",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);

    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;
}
var sj_type = 0;// 0 关闭   1 地址   2 部件 3 地址部件
//x,y,radius,layername,m_showGraphic,isGoTo
var sj_radius;
var sj_layername;
var sj_X;
var sj_Y;
var sjDraging = false;

function sj_mapResize() {
    switch (sj_type) {
        case 0:
        {
            return;
            break;
        }
        case 1:
        {
            GetAddressByXY(m_view.center.x, m_view.center.y, 50);
            break;
        }
        case 2:
        case 3:
        {
            if (sj_type == 3) {
                GetAddressByXY(m_view.center.x, m_view.center.y, 50);
            }
            var layerId = GetFeatureLayerIdbyName(sj_layername);
            if (layerId == -1) {
                // alert("没有此图层");
                window.parent.postMessage(
                    {
                        method: "queryByGeometryAndLayer",
                        data: ["没有此图层"]
                    },
                    '*'
                );
            } else {
                require([
                    "esri/geometry/Point",
                    "esri/geometry/geometryEngine",
                    "esri/geometry/Circle",
                    "esri/layers/FeatureLayer"
                ], function (Point, geometryEngine, Circle, FeatureLayer) {
                    var buffer = new Circle({
                        radius: sj_radius,
                        radiusUnit: "meters",
                        center: {
                            x: m_view.center.x - 0,
                            y: m_view.center.y - 0,
                            spatialReference: m_view.spatialReference
                        }
                    });
                    var quakesUrl = dyLayer.url + "/" + layerId;
                    var quakesLayer = new FeatureLayer({
                        url: quakesUrl,
                        outFields: ["*"],
                        visible: false
                    });
                    var query = quakesLayer.createQuery();
                    // query.where = "mag >= " + magSlider.values[0];
                    query.geometry = buffer;
                    query.spatialRelationship = "intersects";
                    quakesLayer.queryFeatures(query).then(function (results) {
                        // var test = results;
                        var attributesArr = [];
                        if (results.features.length == 0) {
                            window.parent.postMessage(
                                {
                                    method: "queryByGeometryAndLayer",
                                    data: []
                                },
                                '*'
                            );
                            return;
                        }
                        for (var i = 0; i < results.features.length; i++) {
                            attributesArr.push(results.features[i].attributes);
                        }
                        window.parent.postMessage(
                            {
                                method: "queryByGeometryAndLayer",
                                data: [attributesArr]
                            },
                            '*'
                        );
                    });
                    ;
                });
            }
            break;
        }
    }
}

function GetAddressByXY(x, y, radius) {
    var layerId = GetFeatureLayerIdbyName("门牌");
    require([
        "esri/geometry/Point",
        "esri/geometry/geometryEngine",
        "esri/geometry/Circle",
        "esri/layers/FeatureLayer"
    ], function (Point, geometryEngine, Circle, FeatureLayer) {
        // x = m_view.center.x;
        // y = m_view.center.y;
        // x = 0;
        // y = 0;
        var buffer = new Circle({
            radius: radius - 0,
            radiusUnit: "meters",
            center: {
                x: x - 0,
                y: y - 0,
                spatialReference: m_view.spatialReference
            }
        });
        var quakesUrl = dyLayer.url + "/" + "253";//layerId;
        var quakesLayer = new FeatureLayer({
            url: quakesUrl,
            outFields: ["*"],
            visible: false
        });
        var query = quakesLayer.createQuery();
        // query.where = "mag >= " + magSlider.values[0];
        query.geometry = buffer;
        query.spatialRelationship = "intersects";
        quakesLayer.queryFeatures(query).then(function (results) {
            // var test = results;
            var attributesArr = [];
            if (results.features.length == 0) {
                if (radius == 50) {
                    GetAddressByXY(x, y, 200);
                }
                else {
                    window.parent.postMessage(
                        {
                            method: "addressdataCallback",
                            data: []
                        },
                        '*'
                    );
                }
                return;
            }
            for (var i = 0; i < results.features.length; i++) {
                attributesArr.push(results.features[i]);
            }
            function sortAttributesArr(a, b) {
                var dx = Math.abs(x - a.geometry.x);
                var dy = Math.abs(y - a.geometry.y);
                var dis = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));

                var dx1 = Math.abs(x - b.geometry.x);
                var dy1 = Math.abs(y - b.geometry.y);
                var dis1 = Math.sqrt(Math.pow(dx1, 2) + Math.pow(dy1, 2));

                return dis - dis1;
            }

            attributesArr.sort(sortAttributesArr);
            var addressdata = [];
            addressdata.push(attributesArr[0].attributes.道路名 + ' ' +
                attributesArr[0].attributes.门牌号 + ' ' + attributesArr[0].attributes.名称);
            var temp = 5;
            // if(attributesArr.length<5){
            //     temp = attributesArr.length;
            // }
            // for(var i =0;i<temp;i++){
            //     addressdata.push(attributesArr[i].attributes);
            // }
            window.parent.postMessage(
                {
                    method: "addressdataCallback",
                    data: [addressdata]
                },
                '*'
            );
        });
        ;
    });
}

function ShowPolygonandText(type, name, text) {

    var layername;
    var typename;
    var layer;
    var layerId;
    if (type == 1) {
        layername = "街道乡镇";
        typename = "街道名称";
         layer = getLayerByLayerId("动态数据");
         layerId = getSubLayerIdbyName(layer, "街道乡镇");
    }
    else if (type == 2) {
        layername = "村居委会";
        typename = "名称";
         layer = getLayerByLayerId("density_1");
         layerId = getSubLayerIdbyName(layer, layername);
    }

    if (layerId == -1)
        return;
    // 街道名称: 万祥镇
    require(["esri/tasks/QueryTask", "esri/tasks/support/Query", "esri/layers/FeatureLayer", "dojo/_base/array", "dojo/dom", "esri/Graphic",
            "esri/geometry/Point"],
        function (QueryTask, Query, FeatureLayer, arrayUtils, dom, Graphic, Point) {
            var urlI = dyLayer.url + "/" + layerId;
            var qTask = new QueryTask({
                url:   layer.url + "/" + layerId
            });
            var params = new Query({
                geometry: queryExtent,
                returnGeometry: true,
                outFields: ["*"]
            });
            // params.spatialRelationship = "intersects";
            // params.geometry = geo || null;
            params.where = typename + "='" + name + "'";
            qTask.execute(params).then(getResults).otherwise(promiseRejected);
            function getResults(response) {
                if (response.features.length == 0) {
                    return;
                }
                var polygon = response.features[0].geometry;
                var fillSymbol = {
                    type: "simple-fill",
                    color: [255, 255, 255, 0],
                    style: "solid",
                    outline: {
                        color: [255, 0, 0],
                        width: 3
                    }
                };
                var polygonGraphic = new Graphic({
                    geometry: polygon,
                    symbol: fillSymbol,
                });

                var point = point = {
                    type: "point",
                    x: polygon.extent.center.x,
                    y: polygon.extent.center.y,
                    spatialReference: m_view.spatialReference
                };
                // var textSymbol = {
                //     type: "text", // autocasts as new TextSymbol()
                //     color: [0,255,0],
                //     text: text, // esri-icon-map-pin
                //     font: {
                //         // autocasts as new Font()
                //         size: 36,
                //         family: "CalciteWebCoreIcons"
                //     }
                // };
                var textSymbol = {
                    type: "text",  // autocasts as new TextSymbol()
                    color: "black",
                    text: text,
                    font: {  // autocasts as new Font()
                        size: 14,
                        weight: "bold"
                    }
                };
                var pointGraphic = new Graphic({
                    geometry: point,
                    symbol: textSymbol
                });
                GraphicsLayer_myLayer.add(polygonGraphic);
                GraphicsLayer_myLayer.add(pointGraphic);

                // m_view.goTo(pointGraphic);
            }

            function promiseRejected(err) {
                console.error("错误信息: ", err.message);
            }
        });
}

//高亮边界
function highLightArea(layerName, where, colorList, orderField) {
    // var layerId = GetFeatureLayerIdbyName(layerName);
    var layer = getLayerByLayerId("density_1");
    var layerId = getSubLayerIdbyName(layer, layerName);
    if (!where) {
        where = "1=1";
    }


    if (layerId == -1)
        return;
    require(["esri/tasks/QueryTask", "esri/tasks/support/Query", "esri/layers/FeatureLayer", "dojo/_base/array", "dojo/dom", "esri/Graphic",
            "esri/geometry/Point"],
        function (QueryTask, Query, FeatureLayer, arrayUtils, dom, Graphic, Point) {
            var polygonGraphicArray = [];
            var pointGraphicArray = [];
            var urlI = layer.url + "/" + layerId;
            var qTask = new QueryTask({
                url: urlI
            });
            var params = new Query({
                returnGeometry: true,
                outFields: ["*"]
            });
            // params.spatialRelationship = "intersects";
            // params.geometry = geo || null;
            params.where = where;
            qTask.execute(params).then(getResults).catch(promiseRejected);
            function getResults(response) {
                var popArray=[];
                if (response.features.length == 0) {
                    return;
                }
                var textColor3="rgba(0, 0, 0, 0.5) "
                $.each(response.features, function (index, feature) {
                    var color = [255, 0, 0, 0.5];
                    var textColor = "black";
                    var textColor2="black";
                  
                    var text = "";
                    var text2="";
                    var text3="";
                    if (orderField) {
                        for (var i = 0; i < colorList.length; i++) {
                            if (colorList[i].name == feature.attributes[orderField]) {
                                color = colorList[i].color;
                                text = colorList[i].text;

                                if (colorList[i].textColor) {
                                    textColor = colorList[i].textColor
                                }
                                if (colorList[i].textColor2) {
                                    textColor2 = colorList[i].textColor2
                                }
                                if (colorList[i].textColor3) {
                                    textColor3 = colorList[i].textColor3
                                }
                                if (colorList[i].text2) {
                                    text2 = colorList[i].text2;
                                }
                                if (colorList[i].text3) {
                                    text3 = colorList[i].text3;
                                }
                            }
                        }
                    }
                    var geometry = feature.geometry;

                    var fillSymbol;
                    if (geometry.type == "polygon") {
                        fillSymbol = {
                            type: "simple-fill",
                            color: color,
                            style: "solid",
                            outline: {
                                color: color,
                                width: 2
                            }
                        };
                    } else {
                        if (geometry.type == "polyline") {
                            fillSymbol = {
                                type: "simple-line",
                                color: color,
                                width: 3
                            };
                        } else {
                            if (geometry.type == "point") {
                                fillSymbol = {
                                    type: "simple-marker",
                                    color: color,
                                    style: "circle",
                                    size: 10
                                };
                            }
                        }
                    }
                    var polygonGraphic = new Graphic({
                        geometry: geometry,
                        symbol: fillSymbol,
                        attributes: feature.attributes
                    });

                    var point = {
                        type: "point",
                        x: geometry.extent.center.x,
                        y: geometry.extent.center.y,
                        spatialReference: m_view.spatialReference
                    };
                    var point2 = {
                        type: "point",
                        x: geometry.extent.center.x,
                        y: geometry.extent.center.y,
                        spatialReference: m_view.spatialReference
                    };
                    var textSymbol = {
                        type: "text",  // autocasts as new TextSymbol()
                        color: textColor,
                        text: text,
                        font: {  // autocasts as new Font()
                            size: 14,
                            weight: "bold"
                        }
                    };
                    var pointGraphic = new Graphic({
                        geometry: point,
                        symbol: textSymbol,
                     attributes: feature.attributes
                    });
                    var textSymbol2 = {
                        type: "text",  // autocasts as new TextSymbol()
                        color: textColor2,
                        text: text2,
                        font: {  // autocasts as new Font()
                            size: 14
                        },
                        yoffset: "-25px"
                    };
                    var pointGraphic2 = new Graphic({
                        geometry: point2,
                        symbol: textSymbol2
                    });
                    polygonGraphicArray.push(polygonGraphic);
                     pointGraphicArray.push(pointGraphic);
                    pointGraphicArray.push(pointGraphic2);
                    if(text3!=""){
                        popArray.push({
                            //地图坐标
                            x: geometry.extent.center.x,
                            y: geometry.extent.center.y,
                            //popup内容的文字，只是个示范，当然格式不限
                            content: text3,
                            //气泡窗口div的id唯一标识
                            id: "areaHigh_"+index
                        })
                    }
                   
                });
                if(popArray.length>0){
                    popupCloseAll();
                    popupInfos = [];
                    popupInit(popArray,false);
                    $(".leaflet-popup-content-wrapper").css("cssText","background-color:" +textColor3+   "!important;");
                    $(".leaflet-popup-tip").css("cssText","background-color:" +textColor3+    "!important; ");
                }
                GraphicsLayer_myLayer.removeAll();
                GraphicsLayer_myLayer.addMany(polygonGraphicArray);
                GraphicsLayer_myLayer.addMany(pointGraphicArray);
             
             
                // m_view.goTo(polygonGraphicArray);
            }

            function promiseRejected(err) {
                console.error("错误信息: ", err.message);
            }

        });
}
function goToZoom(x, y) {

    require(["esri/Camera", "esri/geometry/Point", "esri/Graphic"], function (Camera, Point, Graphic) {
        var pt = new Point({
            x: x - 0,
            y: y - 0,
            spatialReference: m_view.spatialReference
        });
        var pointGraphic = new Graphic({
            geometry: pt
        });
        m_view.goTo({
            target: pointGraphic

        });
    })

}
//echarts layer
var chartLayer;
var chartLayerSize;
//迁移图
function echartsRoute(dataArray, color, imgSrc, imgsize) {
    var series = [];
    if (!color) {
        color = "#FF0000";
    }
    if (!imgsize) {
        imgsize = 40
    }
    chartLayerSize = imgsize;

    imgsize = chartLayerSize - (chartLayerSize * (12 - m_view.zoom) * 0.05);//zoom每级差5%
    if (!imgSrc) {
        imgSrc = "circle";
    }
    else {
        imgSrc = "image://" + imgSrc;
    }
    if (dataArray.length == 0) {
        return;
    }

    dataArray.forEach(function (item, i) {
        series.push({
                name: item[0] + ' Top10',
                type: 'lines',
                coordinateSystem: 'arcgis',
                zlevel: 1,
                effect: {
                    show: true,
                    period: 6,
                    trailLength: 0.7,
                    color: '#fff',
                    symbolSize: 3
                },
                lineStyle: {
                    normal: {
                        color: color,
                        width: 0,
                        curveness: 0.2
                    }
                },
                data: convertData(item)
            },
            {
                name: item[0] + ' Top10',
                type: 'lines',
                coordinateSystem: 'arcgis',
                zlevel: 2,
                symbol: ['none', 'arrow'],
                symbolSize: 10,
                effect: {
                    show: true,
                    period: 6,
                    trailLength: 0,
                    symbol: imgSrc,
                    symbolSize: imgsize
                },
                lineStyle: {
                    normal: {
                        color: color,
                        width:  item[1].width? item[1].width:1,
                        opacity: 0.6,
                        curveness: 0.2
                    }
                },
                data: convertData(item)
            }
        );
    });
    require([
        "lib/echartsLayer"
    ], function (echartsLayer) {
        chartLayer = new echartsLayer(m_view);
        var option = {
            series: series
        };
        chartLayer.setChartOption(option);
    });
    //console.log(echarts);
}
var chartLayer2;
function echartsWaterSourceToWorkRoute(dataArray, color, imgSrc, imgsize) {
    var series = [];
    if (!color) {
        color = "#FF0000";
    }
    if (!imgsize) {
        imgsize = 40
    }
    chartLayerSize = imgsize;

    // imgsize = chartLayerSize - (chartLayerSize * (12 - m_view.zoom) * 0.05);//zoom每级差5%
    if (!imgSrc) {
        imgSrc = "circle";
    }
    else {
        imgSrc = "image://" + imgSrc;
    }
    if (dataArray.length == 0) {
        return;
    }

    dataArray.forEach(function (item, i) {
        series.push({
                name: item[0] + ' Top10',
                type: 'lines',
                coordinateSystem: 'arcgis',
                zlevel: 1,
                effect: {
                    show: true,
                    period: 6,
                    trailLength: 0.7,
                    color: color,
                    symbol:'rect',
                    symbolSize: imgsize
                },
                lineStyle: {
                    normal: {
                        color: color,
                        width: 0,
                        curveness: 0.2
                    }
                },
                data: convertData(item)
            },
            {
                name: item[0] + ' Top10',
                type: 'lines',
                coordinateSystem: 'arcgis',
                zlevel: 2,
                symbol: ['none', 'arrow'],
                symbolSize: 10,
                effect: {
                    show: true,
                    period: 6,
                    trailLength: 0,
                    symbol: imgSrc,
                    symbolSize: imgsize
                },
                lineStyle: {
                    normal: {
                        color: color,
                        width: 1,
                        opacity: 0.6,
                        curveness: 0.2
                    }
                },
                data: convertData(item)
            }
        );
    });
    require([
        "lib/echartsLayer"
    ], function (echartsLayer) {
        chartLayer2 = new echartsLayer(m_view);
        var option = {
            series: series
        };
        chartLayer2.setChartOption(option);
    });
}
var chartLayer3;
function echartsWaterWorkToAreaRoute(dataArray, color, imgSrc, imgsize) {
    var series = [];
    if (!color) {
        color = "#FF0000";
    }
    if (!imgsize) {
        imgsize = 40
    }
    chartLayerSize = imgsize;

    // imgsize = chartLayerSize - (chartLayerSize * (12 - m_view.zoom) * 0.05);//zoom每级差5%
    if (!imgSrc) {
        imgSrc = "circle";
    }
    else {
        imgSrc = "image://" + imgSrc;
    }
    if (dataArray.length == 0) {
        return;
    }

    dataArray.forEach(function (item, i) {
        series.push({
                name: item[0] + ' Top10',
                type: 'lines',
                coordinateSystem: 'arcgis',
                zlevel: 1,
                effect: {
                    show: true,
                    period: 6,
                    trailLength: 0.7,
                    color: color,
                    symbol:'rect',
                    symbolSize: imgsize
                },
                lineStyle: {
                    normal: {
                        color: color,
                        width: 0,
                        curveness: 0.2
                    }
                },
                data: convertData(item)
            },
            {
                name: item[0] + ' Top10',
                type: 'lines',
                coordinateSystem: 'arcgis',
                zlevel: 2,
                symbol: ['none', 'arrow'],
                symbolSize: 10,
                effect: {
                    show: true,
                    period: 6,
                    trailLength: 0,
                    symbol: imgSrc,
                    symbolSize: imgsize
                },
                lineStyle: {
                    normal: {
                        color: color,
                        width: 1,
                        opacity: 0.6,
                        curveness: 0.2
                    }
                },
                data: convertData(item)
            }
        );
    });
    require([
        "lib/echartsLayer"
    ], function (echartsLayer) {
        chartLayer3 = new echartsLayer(m_view);
        var option = {
            series: series
        };
        chartLayer3.setChartOption(option);
    });
    //console.log(echarts);
}
var convertData = function (data) {
    var res = [];

    for (var i = 0; i < data.length; i++) {
        var fromCoord = data[0].xy;
        var toCoord = data[1].xy;

        res.push({
            fromName: data[0].name,
            toName: data[1].name,
            coords: [fromCoord, toCoord],
            value: data[1].value
        });

    }
    return res;
};

//气泡
var popupInfos = [];

//初始化列表
function popupInit(popupInfoArray, hasX) {
    m_view.when(function () {
        //监听地图变化事件，对应刷新气泡窗口位置
        m_view.watch("extent", function () {
            relocatePopup();
        });
        m_view.watch("rotation", function () {
            relocatePopup();
        });
        //地图加载完，初始化气泡窗口

    });
    //popup初始化
    popupInfos = popupInfoArray;

    for (var i = 0; i < popupInfos.length; i++) {
        var popupInfo = popupInfos[i];
        //坐标转换
        var mapPoint = {
            x: popupInfo.x,
            y: popupInfo.y,
            spatialReference: m_view.spatialReference
        };
        var screenPoint = m_view.toScreen(mapPoint);
        var obj = {};
        obj.x = screenPoint.x;
        obj.y = screenPoint.y;
        obj.content = popupInfo.content;
        obj.id = popupInfo.id;
        loadinfoWindow(obj, hasX);
    }


}

function relocatePopup(e) {
    for (var i = 0; i < popupInfos.length; i++) {
        var popupInfo = popupInfos[i];
        //坐标转换
        var mapPoint = {
            x: popupInfo.x,
            y: popupInfo.y,
            spatialReference: m_view.spatialReference
        }
        var screenPoint = m_view.toScreen(mapPoint);
        var obj = {};
        obj.x = screenPoint.x;
        obj.y = screenPoint.y;
        obj.content = popupInfo.content;
        obj.id = popupInfo.id;
        //刷新气泡窗口位置
        positionPopUp(obj);
    }


}
//显示所有气泡窗口
function popupShowAll() {
    for (var i = 0; i < popupInfos.length; i++) {
        var popupInfo = popupInfos[i];
        showinfoWindow(popupInfo.id);
    }
}

//隐藏所有气泡窗口
function popupCloseAll(id) {
    if(!id){
        id="";
    }
    if (popupInfos.length > 0) {
        if(id=="viewClick"){
            if(popupInfos[0].id){
                if(popupInfos[0].id.indexOf("areaHigh_")!=-1){
                    return
                }
            }

        }
        postToParentPageMethed("closePopupReturn", []);
    }
    for (var i = 0; i < popupInfos.length; i++) {
        var popupInfo = popupInfos[i];
        hideinfoWindow(popupInfo.id);
    }
    popupInfos = [];
}
function closePopupReturn(obj) {
    postToParentPageMethed("closePopupReturn", [obj]);
}
function loadinfoWindow(obj, hasX) {
    var xStr = "";

    if (hasX) {
        xStr = '<a class="leaflet-popup-close-button" id="leaflet-popup-close' + obj.id + '" href="#" onclick="closePopupReturn(&apos;' + obj.id +
            '&apos;)">×</a>'
    }
    //动态添加气泡窗口DIV
    var infoDiv = '<div id="trackPopUp' + obj.id + '" class="leaflet-popup">' +
        '' + xStr +
        '<div class="leaflet-popup-content-wrapper">' +
        '<div id="' + obj.id + '" class="leaflet-popup-content" style=" "></div>' +
        '</div>' +
        '<div class="leaflet-popup-tip-container">' +
        '<div class="leaflet-popup-tip"></div>' +
        '</div>' +
        '</div>';
    $("#mapDiv").append(infoDiv);
    //填充内容
    $('#' + obj.id).append(obj.content);
    //刷新气泡窗口位置
    positionPopUp(obj);
    //气泡窗口关闭事件
    $('#leaflet-popup-close' + obj.id).click(function () {
        $('#trackPopUp' + obj.id).remove();
        for (var i = popupInfos.length - 1; i >= 0; i--) {
            if (obj.id == popupInfos[i].id) {
                popupInfos.splice(i, 1);
            }
        }
    });
}

//显示指定气泡窗口
function showinfoWindow(id) {
    $('#trackPopUp' + id).show();
}
//隐藏指定气泡窗口
function hideinfoWindow(id) {
    $('#trackPopUp' + id).remove();
}

function positionPopUp(obj) {
    var o = document.getElementById("trackPopUp" + obj.id);
    var w = o.clientWidth || o.offsetWidth;
    var h = o.clientHeight || o.offsetHeight;

    $('#trackPopUp' + obj.id).css('transform', 'translate3d(' + (obj.x - (w / 2)) + 'px, ' + (obj.y - (h)) + 'px, 0)');

}

function colorRgba(sHex, alpha) {
    // 十六进制颜色值的正则表达式
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
    /* 16进制颜色转为RGB格式 */
    var sColor = sHex.toLowerCase()
    if (sColor && reg.test(sColor)) {
        if (sColor.length === 4) {
            var sColorNew = '#'
            for (var i = 1; i < 4; i += 1) {
                sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
            }
            sColor = sColorNew
        }
        //  处理六位的颜色值
        var sColorChange = []
        for (var i = 1; i < 7; i += 2) {
            sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)))
        }
        // return sColorChange.join(',')
        // 或
        return 'rgba(' + sColorChange.join(',') + ',' + alpha + ')'
    } else {
        return sColor;
    }
}