
dojo.require("esri.map");
dojo.require("esri.symbol");
dojo.require("esri.tasks.geometry");
dojo.require("esri.tasks.GeometryService");
dojo.require("esri.tasks.BufferParameters");
dojo.require("esri.toolbars.draw");
dojo.require("esri.geometry.Extent");
dojo.require("esri.layers.MapImageLayer");
dojo.require("esri.layers.TileLayer");
//dojo.require("esri.layers");
var fullExtent;
// var infoTemplate = new esri.InfoTemplate("${FIELD_NAME}", "Field ID : ${FIELD_KID}<br />Produces Gas : ${PROD_GAS}<br />Produces Oil : ${PROD_OIL}<br />Status : ${STATUS}");

function init() {
    map = new esri.Map("mapDiv", {
        sliderOrientation: "vertical",
        sliderPosition: "top-right",
        sliderStyle: "large",
        logo:false
    });

    var view = new MapView({
        container: "mapDiv",  // Reference to the DOM node that will contain the view
        map: map               // References the map object created in step 3
    });
    dyAddMapLayerByConfig();
    AddMapGraphicLayers();
    map.on("load", LoadInfo);
}

function dyAddMapLayerByConfig(){
    var serverUrl;
    var serverType;
    var serverLabel;
    var serverVisible;
    var xmlUtil = new XMLUtil();
    var xmlDoc = xmlUtil.loadXmlFromFile("config/config_local.xml");
    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 esri.geometry.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 esri.tasks.GeometryService(serverUrl);
            break;
        }
        case "tiled":{
            layer = new esri.layers.MapImageLayer({ url:serverUrl,"id": serverLabel });
            layer.visible = serverVisible;
            break;
        }
        case "dynamic":{
            layer = new esri.layers.TileLayer({url:serverUrl, "id": serverLabel });
            layer.visible = serverVisible;
            break;
        }
        case "featurelayer":{
            break;
        }
    }
    map.addLayer(layer);
}

function changeMapLayer(layerName,type){
    if(isEmptyValue(type) == true){
        type = "tiled";
    }
    for (var i=0; i<map.layerIds.length;i++){
        var layeridName = map.layerIds[i];
        var BaseLayer = map._layers[layeridName];
        if(type = "tiled"){
            if(BaseLayer.declaredClass == "esri.layers.ArcGISTiledMapServiceLayer"){
                if(layeridName == layerName){
                    BaseLayer.show();
                }
                else{
                    BaseLayer.hide();
                    // map.getLayer(layeridName).hide();
                }
            }
        }
        else{
            if(BaseLayer.declaredClass == "esri.layers.ArcGISDynamicMapServiceLayer"){
                if(layeridName == layerName){
                    BaseLayer.show();
                }
                else{
                    BaseLayer.hide();
                }
            }
        }
        // map.getLayer(layerName).show();
    }
}
var drawtool;
var initExtent;
var FullExtent;
var geometryService;
var GraphicsLayer_labelLayer;//查询结果标签图层
var GraphicsLayer_myLayer;//查询结果撒点图层
var GraphicsLayer_identityLayer;//点查询结果图层
var GraphicsLayer_extendLayer;//查询结果边界范围撒点图层
var GraphicsLayer_fickerLayer;//闪烁特效图层
var GraphicsLayer_DrawLayer;//绘制图层
var GraphicsLayer_flyTipLayer;//飞行提示图层
//地图添加公共标注图层
function AddMapGraphicLayers()
{
    GraphicsLayer_labelLayer = new esri.layers.GraphicsLayer();
    GraphicsLayer_myLayer = new esri.layers.GraphicsLayer();
    GraphicsLayer_identityLayer = new esri.layers.GraphicsLayer();
    GraphicsLayer_extendLayer = new esri.layers.GraphicsLayer();
    GraphicsLayer_fickerLayer = new esri.layers.GraphicsLayer();
    GraphicsLayer_DrawLayer = new esri.layers.GraphicsLayer();
    GraphicsLayer_flyTipLayer = new esri.layers.GraphicsLayer();

    map.addLayer(GraphicsLayer_labelLayer);
    map.addLayer(GraphicsLayer_identityLayer);
    map.addLayer(GraphicsLayer_extendLayer);
    map.addLayer(GraphicsLayer_DrawLayer);
    map.addLayer(GraphicsLayer_flyTipLayer);
    map.addLayer(GraphicsLayer_myLayer);
    map.addLayer(GraphicsLayer_fickerLayer);
}

var dynamicLayerURL;  //动态查询图层URL
//通过where条件查询图层信息
function QueryObjectByWhere(LayerName,where,returnFields,KeyValue){
    KeyValue = KeyValue?KeyValue:"Query";
    var query = new esri.tasks.Query();
    var QueryLayerID = GetLayerIdbyName(LayerName);
    if(QueryLayerID == -1){
        return "无查询图层";
    }
    var queryTask = new esri.tasks.QueryTask(dynamicLayerURL+"/"+QueryLayerID);
    queryTask.where = " 1=1 ";
    if(where != ""){
        query.where = where;
    }
    query.outSpatialReference = 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);
            // return "查询不成功！";
        });
}

function QueryObjectByGeometry(LayerName,queryGeometry,where,returnFields,KeyValue) {
    KeyValue = KeyValue ? KeyValue : "Query";

    var query = new esri.tasks.Query();
    var QueryLayerID = GetLayerIdbyName(LayerName);
    if (QueryLayerID == -1) {
        return "无查询图层";
    }
    var queryTask = new esri.tasks.QueryTask(dynamicLayerURL + "/" + QueryLayerID);
    if (queryGeometry != null) {
        queryGeometry.spatialReference = map.spatialReference;
        query.geometry = queryGeometry;
    }
    queryTask.where = " 1=1 ";
    if (where != "") {
        query.where = where;
    }
    query.outSpatialReference = map.spatialReference;
    query.returnGeometry = true;
    query.outFields = ["*"];
    if (returnFields != "") {
        query.outFields  = returnFields;
    }
    queryTask.execute(query,
        function handleQueryResultByGeometry(results) {
            QueryObjectByWhereCompHandle(results, KeyValue);
        }
        , function errorHandlerByGeometry(err) {
            QueryObjectByWhereFaultHandle("查询不成功！",KeyValue);
        });
}

//-----------------------------------------Symbol------------------------------------------------------------------------------
function GetSymbol_SimpleMarkerSymbol(style,size,color,alpha,outlineStyle,outline_Color,outlineAlpha,outlineWidth)
{
    style = style?style:esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE;
    size = size?size:10;
    color = color?color:"#ff0000";
    alpha = alpha?alpha:0.8;
    outlineStyle = outlineStyle?outlineStyle:esri.symbol.SimpleLineSymbol.STYLE_SOLID;
    outline_Color = outline_Color?outline_Color:"#ff0000";
    outlineAlpha = outlineAlpha?outlineAlpha:0.9;
    outlineWidth = outlineWidth?outlineWidth:1;
    //(style, size, outline, color) style:STYLE_CIRCLE;STYLE_CROSS;STYLE_DIAMOND;STYLE_PATH;STYLE_SQUARE;STYLE_X
    var defaultPointSymbol ;
    require(["esri/symbols/SimpleMarkerSymbol", "esri/symbols/PictureFillSymbol", "esri/symbols/SimpleLineSymbol","esri/symbols/SimpleFillSymbol","esri/Color"],
        function(SimpleMarkerSymbol,PictureFillSymbol,SimpleLineSymbol,SimpleFillSymbol,Color) {
            defaultPointSymbol = new SimpleMarkerSymbol();
            defaultPointSymbol.style = style;
            defaultPointSymbol.size  = size;
            //SetPointColor
            var PointColor = new Color(color);
            PointColor.a = alpha;
            defaultPointSymbol.color = PointColor;
            //SetOutLine
            var outlineColor = new Color(outline_Color);
            outlineColor.a = outlineAlpha;
            defaultPointSymbol.outline = new SimpleLineSymbol(outlineStyle,outlineColor,outlineWidth);
            return defaultPointSymbol;
        });
    return defaultPointSymbol;
}

function GetSymbol_SimpleLineSymbol(style, color, width ,alpha)
{
    style = style?style:esri.symbol.SimpleLineSymbol.STYLE_SOLID;
    color = color?color:"#ff0000";
    width = width?width:2;
    alpha = alpha?alpha:1;
    //(style, color, width)style:STYLE_DASH;STYLE_DASHDOT;STYLE_DASHDOTDOT;STYLE_DOT;STYLE_LONGDASH;STYLE_LONGDASHDOT;STYLE_NULL;STYLE_SHORTDASH;STYLE_SHORTDASHDOT;STYLE_SHORTDASHDOTDOT;STYLE_SHORTDOT;STYLE_SOLID
    var defaultLineSymbol ;
    require(["esri/symbols/SimpleMarkerSymbol", "esri/symbols/PictureFillSymbol", "esri/symbols/SimpleLineSymbol","esri/symbols/SimpleFillSymbol","esri/Color"],
        function(SimpleMarkerSymbol,PictureFillSymbol,SimpleLineSymbol,SimpleFillSymbol,Color) {
            defaultLineSymbol = new SimpleLineSymbol();
            defaultLineSymbol.style = style;
            defaultLineSymbol.width  = width;
            //SetLineColor
            var LineColor = new Color(color);
            LineColor.a = alpha;
            defaultLineSymbol.color = LineColor;

            return defaultLineSymbol;
        });
    return defaultLineSymbol;
}

function GetSymbol_SimpleFillSymbol(style, color,alpha,outlineStyle,outline_Color,outlineAlpha,outlineWidth)
{
    if(style == undefined){
        style = esri.symbol.SimpleFillSymbol.STYLE_SOLID;
    }
    else{
    }
    // style = (style==undefined)?style:esri.symbol.SimpleFillSymbol.STYLE_SOLIDE;
    color = color!=undefined?color:"#ff0000";
    alpha = alpha!=undefined?alpha:0.3;
    outlineStyle = outlineStyle!=undefined?outlineStyle:esri.symbol.SimpleLineSymbol.STYLE_SOLID;
    outline_Color = outline_Color!=undefined?outline_Color:"#ff0000";
    outlineAlpha = outlineAlpha!=undefined?outlineAlpha:0.9;
    outlineWidth = outlineWidth!=undefined?outlineWidth:1;
    //(style, outline, color) style:STYLE_BACKWARD_DIAGONAL;STYLE_CROSS ;STYLE_DIAGONAL_CROSS;STYLE_FORWARD_DIAGONAL;STYLE_HORIZONTAL;STYLE_NULL;STYLE_SOLID ;STYLE_VERTICAL
    var defaultFillSymbol ;
    require(["esri/symbols/SimpleMarkerSymbol", "esri/symbols/PictureFillSymbol", "esri/symbols/SimpleLineSymbol","esri/symbols/SimpleFillSymbol","esri/Color"],
        function(SimpleMarkerSymbol,PictureFillSymbol,SimpleLineSymbol,SimpleFillSymbol,Color) {
            defaultFillSymbol = new SimpleFillSymbol();
            defaultFillSymbol.style = style;
            //SetFillColor
            var FillColor = new Color(color);
            FillColor.a = alpha;
            defaultFillSymbol.color = FillColor;
            //SetOutLine
            var outlineColor = new Color(outline_Color);
            outlineColor.a = outlineAlpha;
            defaultFillSymbol.outline = new SimpleLineSymbol(outlineStyle,outlineColor,outlineWidth);
            return defaultFillSymbol;
        });
    return defaultFillSymbol;
}


//-----------------------------------------------Symbol End---------------------------------------------------------------
function QueryResultHandler(results)
{
    var defaultPointSymbol = GetSymbol_SimpleMarkerSymbol();
    var defaultPolylineSymbol = GetSymbol_SimpleLineSymbol();
    var defaultFillSymbol = GetSymbol_SimpleFillSymbol();
    var graphicShow;
    var showFeaturesArray = new Array();
    dojo.forEach(results, function (graphic, i){
        switch (graphic.geometry.type){
            case "point":{
                graphic.symbol = defaultPointSymbol;
                break;
            }
            case "polyline":{
                graphic.symbol = defaultPolylineSymbol;
                break;
            }
            case "polygon":{
                graphic.symbol = defaultFillSymbol;
                break;
            }
        }
        graphicShow = graphic;
        showFeaturesArray.push(graphic);
    });
    AddObjectToMap(map,GraphicsLayer_myLayer,showFeaturesArray);
    // GraphicsLayer_myLayer.add(graphicShow);
}

function AddObjectToMap(myMap, graphicLayer, graphics, isClearLayer,isZoomToObj, zoomBuffer, isFicker, extendFactor,FickerCount,FickerDelay)
{
    isClearLayer = isClearLayer==true?true:false;
    isZoomToObj = isZoomToObj==true?true:false;
    zoomBuffer = zoomBuffer?zoomBuffer:100;
    isFicker = isFicker==true?true:false;
    extendFactor = extendFactor?extendFactor:1.2;
    if (graphicLayer == null || graphics == null || graphics.length <= 0) {
        return;
    }
    if (isClearLayer){
        graphicLayer.clear();
    }
    dojo.forEach(graphics, function (graphic, i) {
        if (graphic.geometry instanceof esri.geometry.Point) {
            var myGeometry = graphic.geometry;
            var pathArray = new Array();
            var pointArray = new Array();
            var centerPoint = myGeometry;
            var beginPoint = new esri.geometry.Point(centerPoint.x - zoomBuffer, centerPoint.y - zoomBuffer, centerPoint.spatialReference);
            pointArray.push(beginPoint);
            var endPoint = new esri.geometry.Point(centerPoint.x + zoomBuffer, centerPoint.y + zoomBuffer, centerPoint.spatialReference);
            pointArray.push(endPoint);
            pathArray.push(pointArray);
            var polyLine = new esri.geometry.Polyline();
            polyLine.spatialReference = myMap.spatialReference;//必须与map保持一致
            polyLine.addPath([new esri.geometry.Point(beginPoint.x, beginPoint.y, beginPoint.spatialReference), new esri.geometry.Point(endPoint.x, endPoint.y, endPoint.spatialReference)]);
            //取对象范围
            if (i == 0) {
                currentExtent = polyLine.getExtent();
            }
            else {
                currentExtent = currentExtent.union(polyLine.getExtent());
            }
        }
        else if (graphic.geometry instanceof esri.geometry.Polyline) {
            if (i == 0) {
                currentExtent = graphic.geometry.getExtent();
            }
            else
            {
                currentExtent = currentExtent.union(graphic.geometry.getExtent());
            }
        }
        else if (graphic.geometry instanceof esri.geometry.Polygon) {
            if (i == 0) {
                currentExtent = graphic.geometry.getExtent();
            }
            else {
                currentExtent = currentExtent.union(graphic.geometry.getExtent());
            }
        }
        graphicLayer.add(graphic);
    });
    if(FickerCount == undefined){
        FickerCount  = 3;
    }
    if(FickerDelay == undefined){
        FickerDelay = 800;
    }
    if (isZoomToObj && isFicker) {
        myMap.setExtent(currentExtent.expand(extendFactor), true);
        fickerGraphic(graphicLayer,graphics,FickerCount,FickerDelay);
    }
    else if (isZoomToObj && !isFicker) {
        myMap.setExtent(currentExtent.expand(extendFactor), true);
    }
    else if (!isZoomToObj && isFicker) {
        fickerGraphic(graphicLayer,graphics,FickerCount,FickerDelay);
    }
}
var interval_;
function fickerGraphic(originLayer,graphics,fickerCount,fickerDelay){
    clearInterval(interval_);
    // originLayer.hide();
    var fickeredCount;//当前闪烁次数
    // originLayer.clear();
    // dojo.forEach(graphics, function (graphic, i) {
    //     originLayer.add(graphic);
    // });
    fickeredCount = 0;
        interval_ = setInterval(function () {
        if(fickeredCount<fickerCount){
            originLayer.hide();
            setTimeout(function () {
                originLayer.show();
            },fickerDelay/2);
        }
        else if (fickeredCount == fickerCount){
            originLayer.show();
            clearInterval(interval_);
        }
        fickeredCount++;
    },fickerDelay);
}

//获取动态图层LayerInfo 及 动态图层URL
function GetDynamicServiceLayer()
{
    var layerInfo;
    for (var i=0; i<map.layerIds.length;i++){
        var layeridName = map.layerIds[i];
        var BaseLayer = map._layers[layeridName];
        if(BaseLayer.declaredClass == "esri.layers.ArcGISDynamicMapServiceLayer"){
            layerInfo = map._layers[layeridName].layerInfos;
            dynamicLayerURL = BaseLayer._url.path;
            return layerInfo;
        }
    }
    return null;
}

//通过图层名称获取图层ID
function GetLayerIdbyName(name)
{
    var index = map.getLayer(name);
    var layerInfo;
    layerInfo = GetDynamicServiceLayer();
    if (layerInfo != null){
        for (var j=0 ; j<layerInfo.length ;j++){
            var currnetLayer = layerInfo[j];
            if(currnetLayer.name == name){
                return currnetLayer.id;
            }
        }
    }
    return -1;
}

//------------------------------------------------------------------GeometryService-----------------------------------------------------------------
function DrawGraphic(drawType){
    drawTool = new esri.toolbars.Draw(map);
    drawTool.on("draw-end", DrawEnd);
    switch (drawType) {
        case "POINT": {
            drawType = esri.toolbars.Draw.POINT;
            break;
        }
        case "MULTI_POINT":{
            drawType = esri.toolbars.Draw.POINT;
            break;
        }
        case "POLYGON":{
            drawType = esri.toolbars.Draw.POLYGON;
            break;
        }
        case "LINE": {
            drawType = esri.toolbars.Draw.POLYLINE;
            break;
        }
        case "CIRCLE":{
            drawType = esri.toolbars.Draw.CIRCLE;
            break;
        }
    }
    GraphicsLayer_DrawLayer.clear();
    // drawType = drawType?drawType:esri.toolbars.Draw.POINT;
    //POINT,MULTI_POINT,POLYLINE,POLYGON,FREEHAND_POLYLINE,FREEHAND_POLYGON,LINE,EXTENT
    drawTool.activate(drawType);
}

function DrawEnd(evt){
    drawTool.deactivate();
    var geometry = evt.geometry;
    var symbol;
    switch (evt.geometry.type){
        case "point":{
            symbol = GetSymbol_SimpleMarkerSymbol();
            break;
        }
        case "polyline":{
            symbol = GetSymbol_SimpleLineSymbol();
            break;
        }
        case "polygon":{
            symbol = GetSymbol_SimpleFillSymbol();
            break;
        }
    }
    var graphic = new esri.Graphic(geometry,symbol);
    AddObjectToMap(map,GraphicsLayer_DrawLayer,[graphic],false,false,100,false,1);
}

function mydraw(drawType){
    drawTool = new esri.toolbars.Draw(map);
    drawTool.on("draw-end", addToMap);
    switch (drawType) {
        case "POINT": {
            drawType = esri.toolbars.Draw.POINT;
            break;
        }
        case "MULTI_POINT":{
            drawType = esri.toolbars.Draw.POINT;
            break;
        }
        case "POLYGON":{
            drawType = esri.toolbars.Draw.POLYGON;
            break;
        }
        case "LINE": {
            drawType = esri.toolbars.Draw.POLYLINE;
            break;
        }
        case "CIRCLE":{
            drawType = esri.toolbars.Draw.CIRCLE;
            break;
        }
    }
    GraphicsLayer_DrawLayer.clear();
    // drawType = drawType?drawType:esri.toolbars.Draw.POINT;
    //POINT,MULTI_POINT,POLYLINE,POLYGON,FREEHAND_POLYLINE,FREEHAND_POLYGON,LINE,EXTENT
    drawTool.activate(drawType);
}

function addToMap(evt) {
    drawTool.deactivate();
    var geometry = evt.geometry;
    //geometry.spatialReference = new esri.SpatialReference({ wkid: 4326 });
    var graphic = new esri.Graphic(geometry, GetSymbol_SimpleMarkerSymbol());

    AddObjectToMap(map,GraphicsLayer_DrawLayer,[graphic],false,false,100,false,1);
    GenerateBuffer([geometry]);
}

function GenerateBuffer(geometriesArray)
{
    if(geometryService)
    {
        var params = new esri.tasks.BufferParameters();
        params.geometries = geometriesArray;

        params.distances = [100];
        params.unit = esri.tasks.GeometryService.UNIT_MILE;
        params.unionResults = true;
        params.bufferSpatialReference = map.spatialReference;
        params.outSpatialReference = map.spatialReference;
        geometryService.buffer(params, doBufferComplete, doBufferFault);
    }
}
function doBufferComplete(event)
{
    var graphic = new esri.Graphic(event[0], GetSymbol_SimpleFillSymbol());
    AddObjectToMap(map,GraphicsLayer_extendLayer ,[graphic],false,true,100,false,1.5)
    //myMap.graphics.add(graphic);
}

function doBufferFault(event)
{
    alert("fault");
}

function setFullExtent(){
    fullExtent.spatialReference = map.spatialReference;
    map.setExtent(fullExtent, true);
}


